motion-prime/models/model.rb in motion-prime-0.2.1 vs motion-prime/models/model.rb in motion-prime-0.3.0

- old
+ new

@@ -26,20 +26,28 @@ end def assign_attributes(new_attributes, options = {}) attributes = new_attributes.symbolize_keys attributes.each do |k, v| - if respond_to?("#{k}=") - send("#{k}=", v) unless options[:skip_nil_values] && v.nil? + if has_attribute?(k) + assign_attribute(k, v) unless options[:skip_nil_values] && v.nil? elsif options[:check_attribute_presence] puts "unknown attribute: #{k}" else raise(NoMethodError, "unknown attribute: #{k}") end end end + def assign_attribute(name, value) + self.send("#{name}=", value) if has_attribute?(name) + end + + def has_attribute?(name) + respond_to?("#{name}=") + end + def attributes_hash self.info.to_hash.symbolize_keys end def new_record? @@ -49,11 +57,11 @@ def persisted? !new_record? end def model_name - self.class.name.underscore + self.class_name_without_kvo.underscore end def inspect "#<#{self.class}:0x#{self.object_id.to_s(16)}> " + MotionPrime::JSON.generate(info) end @@ -95,18 +103,30 @@ # attribute :name # attribute :age # end # # @return Nil - def attribute(name) + def attribute(name, options = {}) attributes << name define_method(name) do |*args, &block| self.info[name] end define_method((name + "=").to_sym) do |*args, &block| - self.info[name] = args[0] + value = args[0] + case options[:type].to_s + when 'integer' then value = value.to_i + when 'float' then value = value.to_f + end unless value.nil? + + self.info[name] = value + end + + if options[:type].to_s == 'boolean' + define_method("#{name}?") do + !!self.info[name] + end end end # Return all model attribute names #