lib/frenchy/model.rb in frenchy-0.0.2 vs lib/frenchy/model.rb in frenchy-0.0.3

- old
+ new

@@ -1,20 +1,21 @@ module Frenchy module Model def self.included(base) base.class_eval do - cattr_accessor :fields + cattr_accessor :fields, :defaults self.fields = {} + self.defaults = {} end base.extend(ClassMethods) end # Create a new instance of this model with the given attributes def initialize(attrs={}) - attrs.each do |k,v| + self.class.defaults.merge(attrs).each do |k,v| if self.class.fields[k.to_sym] send("#{k}=", v) end end end @@ -78,15 +79,15 @@ define_method("#{name}=") do |v| set(name, v.to_s, options) end when :integer define_method("#{name}=") do |v| - set(name, v.to_i, options) + set(name, Integer(v), options) end when :float define_method("#{name}=") do |v| - set(name, v.to_f, options) + set(name, Float(v), options) end when :bool define_method("#{name}=") do |v| set(name, ["true", 1, true].include?(v), options) end @@ -100,31 +101,38 @@ else set(name, DateTime.parse(v), options) end end when :array + options[:default] ||= [] define_method("#{name}=") do |v| set(name, Array(v), options) end when :hash + options[:default] ||= {} define_method("#{name}=") do |v| set(name, Hash[v], options) end else options[:class_name] ||= type.to_s.camelize options[:many] = (name.to_s.singularize != name.to_s) unless options.key?(:many) klass = options[:class_name].constantize define_method("#{name}=") do |v| if options[:many] + options[:default] ||= [] set(name, Frenchy::Collection.new(Array(v).map {|vv| klass.new(vv)})) else set(name, klass.new(v)) end end end self.fields[name.to_sym] = options + + if options[:default] + self.defaults[name.to_sym] = options[:default] + end attr_reader name.to_sym end end end