mirror of
https://github.com/ditkrg/active_model_serializers.git
synced 2026-01-25 07:16:49 +00:00
Merge pull request #170 from FundingGates/master
Support optional types for computed attributes
This commit is contained in:
14
README.md
14
README.md
@@ -252,6 +252,20 @@ class PostSerializer < ActiveModel::Serializer
|
||||
end
|
||||
```
|
||||
|
||||
The type of a computed attribute (like :full_name above) is not easily
|
||||
calculated without some sophisticated static code analysis. To specify the
|
||||
type of a computed attribute:
|
||||
|
||||
```ruby
|
||||
class PersonSerializer < ActiveModel::Serializer
|
||||
attributes :first_name, :last_name, {:full_name => :string}
|
||||
|
||||
def full_name
|
||||
"#{object.first_name} #{object.last_name}"
|
||||
end
|
||||
end
|
||||
```
|
||||
|
||||
If you would like the key in the outputted JSON to be different from its name
|
||||
in ActiveRecord, you can use the `:key` option to customize it:
|
||||
|
||||
|
||||
@@ -82,7 +82,9 @@ module ActiveModel
|
||||
end
|
||||
|
||||
def attribute(attr, options={})
|
||||
self._attributes = _attributes.merge(attr => options[:key] || attr.to_s.gsub(/\?$/, '').to_sym)
|
||||
self._attributes = _attributes.merge(attr.is_a?(Hash) ? attr : {attr => options[:key] || attr.to_s.gsub(/\?$/, '').to_sym})
|
||||
|
||||
attr = attr.keys[0] if attr.is_a? Hash
|
||||
|
||||
unless method_defined?(attr)
|
||||
define_method attr do
|
||||
@@ -184,10 +186,14 @@ module ActiveModel
|
||||
attrs[key] = column.type
|
||||
else
|
||||
# Computed attribute (method on serializer or model). We cannot
|
||||
# infer the type, so we put nil.
|
||||
# infer the type, so we put nil, unless specified in the attribute declaration
|
||||
if name != key
|
||||
attrs[name] = key
|
||||
else
|
||||
attrs[key] = nil
|
||||
end
|
||||
end
|
||||
end
|
||||
|
||||
associations = {}
|
||||
_associations.each do |attr, association_class|
|
||||
|
||||
@@ -563,16 +563,17 @@ class SerializerTest < ActiveModel::TestCase
|
||||
|
||||
# Computed attributes (not real columns or associations).
|
||||
def can_edit; end
|
||||
def can_view; end
|
||||
def drafts; end
|
||||
|
||||
attributes :name, :age, :can_edit
|
||||
attributes :name, :age, {:can_edit => :boolean}, :can_view
|
||||
has_many :posts, :serializer => Class.new
|
||||
has_many :drafts, :serializer => Class.new
|
||||
has_one :parent, :serializer => Class.new
|
||||
end
|
||||
|
||||
assert_equal serializer.schema, {
|
||||
:attributes => { :name => :string, :age => :integer, :can_edit => nil },
|
||||
:attributes => { :name => :string, :age => :integer, :can_edit => :boolean, :can_view => nil },
|
||||
:associations => {
|
||||
:posts => { :has_many => :posts },
|
||||
:drafts => nil,
|
||||
|
||||
Reference in New Issue
Block a user