diff --git a/activemodel/lib/active_model/attributes.rb b/activemodel/lib/active_model/attributes.rb index d7bb2a718e..25375c3905 100644 --- a/activemodel/lib/active_model/attributes.rb +++ b/activemodel/lib/active_model/attributes.rb @@ -120,6 +120,7 @@ module ActiveModel end private + # Writes a value to an attribute by name following aliases if necessary. def write_attribute(attr_name, value) name = attr_name.to_s name = self.class.attribute_aliases[name] || name @@ -132,6 +133,7 @@ module ActiveModel end alias :attribute= :_write_attribute + # Reads a value from an attribute by name following aliases if necessary. def read_attribute(attr_name) name = attr_name.to_s name = self.class.attribute_aliases[name] || name diff --git a/activemodel/test/cases/attributes_test.rb b/activemodel/test/cases/attributes_test.rb index dd4922fe44..c89c382290 100644 --- a/activemodel/test/cases/attributes_test.rb +++ b/activemodel/test/cases/attributes_test.rb @@ -14,6 +14,19 @@ module ActiveModel attribute :string_with_default, :string, default: "default string" attribute :date_field, :date, default: -> { Date.new(2016, 1, 1) } attribute :boolean_field, :boolean + + alias_attribute :integer, :integer_field + alias_attribute :string, :string_field + + def method_that_writes_to_an_attribute + value = read_attribute(:integer_field) + write_attribute(:string_field, value.to_s) + end + + def method_that_writes_to_an_attribute_using_aliases + value = read_attribute(:integer) + write_attribute(:string, value.to_s) + end end class ChildModelForAttributesTest < ModelForAttributesTest @@ -129,5 +142,19 @@ module ActiveModel assert data.frozen? assert_raise(FrozenError) { data.integer_field = 1 } end + + test "attributes can be read and written using the public API" do + data = ModelForAttributesTest.new(integer_field: 20) + data.method_that_writes_to_an_attribute + + assert_equal "20", data.string_field + end + + test "attributes can be read and written using the public API even with aliases" do + data = ModelForAttributesTest.new(integer: 20) + data.method_that_writes_to_an_attribute + + assert_equal "20", data.string + end end end