Skip to content

Conversation

@seanpdoyle
Copy link
Contributor

The problem

The current attribute reading and writing implementation relies upon #method_missing and #respond_to_missing? for access.

When attributes are defined by a schema, it's possible to define methods for them at "declaration time", rather than implementing access entirely through method missing reflection.

The solution

Mix ActiveModel::AttributeMethods into ActiveResource::Base, then hook into schema assignment. When assigning attributes, invoke define_attribute_methods. When the schema is reset to be nil, invoke undefine_attribute_methods.

Similarly, invoke define_attribute_methods on an instance's singleton_class when writing to an attribute through the #load method. Subsequent reads and writes will rely on the ephemeral method (which will invoke #write_attribute and #read_attribute) rather than #method_missing.

The problem
---

The current attribute reading and writing implementation relies
upon `#method_missing` and `#respond_to_missing?` for access.

When attributes are defined by a schema, it's possible to define methods
for them at "declaration time", rather than implementing access entirely
through method missing reflection.

The solution
---

Mix [ActiveModel::AttributeMethods][] into `ActiveResource::Base`, then
hook into `schema` assignment. When assigning attributes, invoke
[define_attribute_methods][]. When the schema is reset to be `nil`,
invoke [undefine_attribute_methods][].

Similarly, invoke `define_attribute_methods` on an instance's
`singleton_class` when writing to an attribute through the `#load`
method. Subsequent reads and writes will rely on the ephemeral method
(which will invoke `#write_attribute` and `#read_attribute`) rather than
`#method_missing`.

[ActiveModel::AttributeMethods]: https://api.rubyonrails.org/classes/ActiveModel/AttributeMethods.html
[define_attribute_methods]: https://api.rubyonrails.org/classes/ActiveModel/AttributeMethods/ClassMethods.html#method-i-define_attribute_methods
[undefine_attribute_methods]: https://edgeapi.rubyonrails.org/classes/ActiveModel/AttributeMethods/ClassMethods.html#method-i-undefine_attribute_methods
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant