diff --git a/lib/enumerated_attribute/integrations/active_record.rb b/lib/enumerated_attribute/integrations/active_record.rb index f4daa6d..3f87a99 100644 --- a/lib/enumerated_attribute/integrations/active_record.rb +++ b/lib/enumerated_attribute/integrations/active_record.rb @@ -97,7 +97,7 @@ class << self def new(*args, &block) result = new_without_enumerated_attribute(*args, &block) params = (!args.empty? && args.first.instance_of?(Hash)) ? args.first : {} - params.each { |k, v| result.write_enumerated_attribute(k, v) } + params.each { |k, v| result.write_enumerated_attribute(k, result[k.to_s]) if self.has_enumerated_attribute?(k.to_s) } result.initialize_enumerated_attributes(true) yield result if block_given? result diff --git a/spec/active_record/active_record_spec.rb b/spec/active_record/active_record_spec.rb index 1092948..b5d26b9 100644 --- a/spec/active_record/active_record_spec.rb +++ b/spec/active_record/active_record_spec.rb @@ -409,6 +409,16 @@ s = RaceCar.find r.id s.lights.should == "--- :off\n" s[:lights].should == "--- :off\n" - end - + end + + it "should use values returned by attribute setter methods" do + r =RaceCar.new(:license_plate_number => ' asdf ') + r.license_plate_number.should == 'asdf' + end + + it "should not generate Active Record attributes on #new for keys that are not really active record attributes" do + r =RaceCar.new(:non_active_record_attribute => 'some value') + r.should_not have_attribute(:non_active_record_attribute) + end + end diff --git a/spec/active_record/race_car.rb b/spec/active_record/race_car.rb index 95f9d9b..f152262 100644 --- a/spec/active_record/race_car.rb +++ b/spec/active_record/race_car.rb @@ -2,6 +2,13 @@ class RaceCar < ActiveRecord::Base enum_attr :gear, %w(reverse ^neutral first second over_drive) enum_attr :choke, %w(^none medium full) + + attr_accessor :non_active_record_attribute + + def license_plate_number=(value) + value = value.strip # remove whitespace from start and end of value + write_attribute(:license_plate_number, value) + end end #gear = enumerated column attribute diff --git a/spec/active_record/test_in_memory.rb b/spec/active_record/test_in_memory.rb index 69a9e2e..7f284b1 100644 --- a/spec/active_record/test_in_memory.rb +++ b/spec/active_record/test_in_memory.rb @@ -12,6 +12,7 @@ connection = ActiveRecord::Base.connection connection.create_table(:race_cars, :force=>true) do |t| t.string :name + t.string :license_plate_number t.enum :gear t.enum :lights t.timestamps