lib/sudo_attributes.rb in sudo_attributes-0.3.0 vs lib/sudo_attributes.rb in sudo_attributes-0.4.0
- old
+ new
@@ -1,50 +1,29 @@
module SudoAttributes
-
+
module Base
- # This is the method that will be called from each model you want to enable SudoAttributes in
- def has_sudo_attributes(*attrs)
- raise "Invalid argument passed to has_sudo_attributes" unless valid_attributes? attrs
+ def sudo_attr_protected(*attrs)
+ Private::set_attributes(self, attrs, :protected)
+ end
- set_protected_attributes(attrs) unless attrs.empty?
-
- self.send :extend, SudoAttributes::ClassMethods
- self.send :include, SudoAttributes::InstanceMethods
+ def sudo_attr_accessible(*attrs)
+ Private::set_attributes(self, attrs, :accessible)
end
-
- private
-
- def valid_attributes?(attrs)
- attrs.empty? || hash_syntax?(attrs) || all_symbols?(attrs)
- end
-
- # True if argument is in the form ":protected => :field1" or ":accessible => :field2"
- def hash_syntax?(attrs)
- return false unless attrs.size == 1
-
- hash = attrs.first
-
- hash.is_a?(Hash) && (hash.has_key?(:protected) || hash.has_key?(:accessible))
- end
-
- # True if argument is in the form ":field1, :field2, :field3"
- def all_symbols?(attrs)
- attrs.all? {|e| e.class == Symbol}
- end
+ end
- # Set the protected attributes depending on the key
- def set_protected_attributes(attrs)
- if all_symbols? attrs
- self.attr_protected *attrs
- else
- key = attrs[0].has_key?(:protected) ? :protected : :accessible
+ module Private
- # Call either attr_protected or attr_accessible
- self.send("attr_#{key}", *attrs[0][key])
+ def self.set_attributes(klass, attrs, type)
+ unless attrs.empty?
+ raise "Invalid argument passed to has_sudo_attributes" unless attrs.all? {|a| a.is_a? Symbol }
+
+ klass.send("attr_#{type}", *attrs)
end
+
+ klass.extend SudoAttributes::ClassMethods
+ klass.send :include, SudoAttributes::InstanceMethods
end
-
end
# Added to ActiveRecord model only if has_sudo_attributes is called
module ClassMethods
def sudo_create(attributes=nil)
@@ -58,23 +37,20 @@
instance.save!
instance
end
def sudo_new(attributes=nil)
- new(attributes, false)
+ instance = new(nil)
+ instance.send(:attributes=, attributes, false)
+ instance
end
end
module InstanceMethods
- def initialize(attributes=nil, attributes_protected=true)
- super(nil)
- send(:attributes=, attributes, attributes_protected)
- end
-
def sudo_update_attributes(new_attributes)
self.send(:attributes=, new_attributes, false)
save
end
end
end
-ActiveRecord::Base.send :extend, SudoAttributes::Base
+ActiveRecord::Base.extend SudoAttributes::Base