mirror of
https://github.com/ditkrg/active_model_serializers.git
synced 2026-01-22 22:06:50 +00:00
Allow specifying attributes with a block
Adapted from https://github.com/rails-api/active_model_serializers/pull/1262
This commit is contained in:
parent
87d18e9c32
commit
6020450fe4
@ -112,19 +112,26 @@ module ActiveModel
|
|||||||
# attributes :id, :recent_edits
|
# attributes :id, :recent_edits
|
||||||
# attribute :name, key: :title
|
# attribute :name, key: :title
|
||||||
#
|
#
|
||||||
|
# attribute :full_name do
|
||||||
|
# "#{object.first_name} #{object.last_name}"
|
||||||
|
# end
|
||||||
|
#
|
||||||
# def recent_edits
|
# def recent_edits
|
||||||
# object.edits.last(5)
|
# object.edits.last(5)
|
||||||
# end
|
# end
|
||||||
def self.attribute(attr, options = {})
|
def self.attribute(attr, options = {}, &block)
|
||||||
key = options.fetch(:key, attr)
|
key = options.fetch(:key, attr)
|
||||||
_attributes_keys[attr] = { key: key } if key != attr
|
_attributes_keys[attr] = { key: key } if key != attr
|
||||||
_attributes << key unless _attributes.include?(key)
|
|
||||||
|
|
||||||
serialized_attributes[key] = ->(object) { object.read_attribute_for_serialization(attr) }
|
if block_given?
|
||||||
|
serialized_attributes[key] = ->(instance) { instance.instance_eval(&block) }
|
||||||
|
else
|
||||||
|
serialized_attributes[key] = ->(instance) { instance.object.read_attribute_for_serialization(attr) }
|
||||||
|
end
|
||||||
|
|
||||||
ActiveModelSerializers.silence_warnings do
|
ActiveModelSerializers.silence_warnings do
|
||||||
define_method key do
|
define_method key do
|
||||||
serialized_attributes[key].call(object)
|
serialized_attributes[key].call(self)
|
||||||
end unless method_defined?(key) || _fragmented.respond_to?(attr)
|
end unless method_defined?(key) || _fragmented.respond_to?(attr)
|
||||||
end
|
end
|
||||||
end
|
end
|
||||||
|
|||||||
@ -71,6 +71,21 @@ module ActiveModel
|
|||||||
|
|
||||||
assert_equal('custom', hash[:blog][:id])
|
assert_equal('custom', hash[:blog][:id])
|
||||||
end
|
end
|
||||||
|
|
||||||
|
PostWithVirtualAttribute = Class.new(::Model)
|
||||||
|
class PostWithVirtualAttributeSerializer < ActiveModel::Serializer
|
||||||
|
attribute :name do
|
||||||
|
"#{object.first_name} #{object.last_name}"
|
||||||
|
end
|
||||||
|
end
|
||||||
|
|
||||||
|
def test_virtual_attribute_block
|
||||||
|
post = PostWithVirtualAttribute.new(first_name: 'Lucas', last_name: 'Hosseini')
|
||||||
|
hash = serializable(post).serializable_hash
|
||||||
|
expected = { name: 'Lucas Hosseini' }
|
||||||
|
|
||||||
|
assert_equal(expected, hash)
|
||||||
|
end
|
||||||
end
|
end
|
||||||
end
|
end
|
||||||
end
|
end
|
||||||
|
|||||||
Loading…
Reference in New Issue
Block a user