Skip to content

Commit

Permalink
Add new behavior of undefine_attribute_methods to CHANGELOG
Browse files Browse the repository at this point in the history
In `1818beb3a3ea5fdb498095d4885f8a7e512f24ca` Rails changed the target
where alias attribute methods are defined. It lead to
`undefine_attribute_methods` to clean alias attribute methods along with
the attribute methods. It was an intended behavior change but it wasn't
properly documented and tested. This commit clarifies the new behavior
in the Active Model changelog along with covering the behavior with tests.
  • Loading branch information
nvasilevski committed Aug 23, 2023
1 parent ed5af00 commit e50fce0
Show file tree
Hide file tree
Showing 3 changed files with 44 additions and 0 deletions.
4 changes: 4 additions & 0 deletions activemodel/CHANGELOG.md
@@ -1,3 +1,7 @@
* `undefine_attribute_methods` undefines alias attribute methods along with attribute methods.

*Nikita Vasilevsky*

* Error.full_message now strips ":base" from the message.

*zzak*
Expand Down
24 changes: 24 additions & 0 deletions activemodel/test/cases/attribute_methods_test.rb
Expand Up @@ -215,6 +215,30 @@ def foo
assert_raises(NoMethodError) { ModelWithAttributes.new.foo }
end

test "#undefine_attribute_methods undefines alias attribute methods" do
topic_class = Class.new do
include ActiveModel::AttributeMethods
define_attribute_methods :title
alias_attribute :subject_to_be_undefined, :title

def attributes
{ title: "Active Model Topic" }
end

private
def attribute(name)
attributes[name.to_sym]
end
end

assert_equal("Active Model Topic", topic_class.new.subject_to_be_undefined)
topic_class.undefine_attribute_methods

assert_raises(NoMethodError, match: /undefined method `subject_to_be_undefined'/) do
topic_class.new.subject_to_be_undefined
end
end

test "accessing a suffixed attribute" do
m = ModelWithAttributes2.new
m.attributes = { "foo" => "bar" }
Expand Down
16 changes: 16 additions & 0 deletions activerecord/test/cases/attribute_methods_test.rb
Expand Up @@ -1022,6 +1022,22 @@ def name
assert subklass.method_defined?(:id), "subklass is missing id method"
end

test "#undefine_attribute_methods undefines alias attribute methods" do
topic_class = Class.new(ActiveRecord::Base) do
self.table_name = "topics"

alias_attribute :subject_to_be_undefined, :title
end

topic = topic_class.new(title: "New topic")
assert_equal("New topic", topic.subject_to_be_undefined)
topic_class.undefine_attribute_methods

assert_raises(NoMethodError, match: /undefined method `subject_to_be_undefined'/) do
topic.subject_to_be_undefined
end
end

test "define_attribute_method works with both symbol and string" do
klass = Class.new(ActiveRecord::Base)
klass.table_name = "foo"
Expand Down

0 comments on commit e50fce0

Please sign in to comment.