You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
The `schema { ... }` interface pre-dates the Active Model Attributes API
(defined as early as [v5.2.0][]), but clearly draws inspiration from
Active Record's Database Schema and Attribute casting (which was
extracted into `ActiveModel::Attributes`).
However, the type information captured in `schema { ... }` blocks or
assigned as `Hash` arguments to `schema=` is purely inert metadata.
Proposal
---
This commit aims to integrate with [ActiveModel::Model][] and
[ActiveModel::Attributes][]. Through the introduction of both modules,
subclasses of `ActiveResource::Base` can benefit from type casting
attributes and constructing instances with default values.
This commit makes minimally incremental changes, prioritizing backwards
compatibility. The reliance on `#respond_to_missing?` and
`#method_missing` is left largely unchanged. Similarly, the `Schema`
interface continues to provide metadata about its attributes through the
`Schema#attr` method (instead of reading from
`ActiveModel::Attributes#attribute_names` or
`ActiveModel::Attributes.attribute_types`).
API Changes
---
To cast values to their specified types, declare the Schema with the
`:cast_values` set to true.
```ruby
class Person < ActiveResource::Base
schema cast_values: true do
integer 'age'
end
end
p = Person.new
p.age = "18"
p.age # => 18
```
To configure inheriting resources to cast values, set the `cast_values`
class attribute:
```ruby
class ApplicationResource < ActiveResource::Base
self.cast_values = true
end
class Person < ApplicationResource
schema do
integer 'age'
end
end
p = Person.new
p.age = "18"
p.age # => 18
```
To set all resources application-wide to cast values, set
`config.active_resource.cast_values`:
```ruby
# config/application.rb
config.active_resource.cast_values = true
```
[v5.2.0]: https://api.rubyonrails.org/v5.2.0/classes/ActiveModel/Attributes/ClassMethods.html
[ActiveModel::Model]: https://api.rubyonrails.org/classes/ActiveModel/Model.html
[ActiveModel::Attributes]: https://api.rubyonrails.org/classes/ActiveModel/Attributes/ClassMethods.html
0 commit comments