mirror of
https://github.com/ditkrg/active_model_serializers.git
synced 2026-01-25 07:16:49 +00:00
Add support for customizing fields
This commit is contained in:
@@ -814,4 +814,58 @@ class SerializerTest < ActiveModel::TestCase
|
||||
]
|
||||
}, actual)
|
||||
end
|
||||
|
||||
def test_can_customize_attributes
|
||||
serializer = Class.new(ActiveModel::Serializer) do
|
||||
attributes :title, :body
|
||||
|
||||
def title
|
||||
object.title.upcase
|
||||
end
|
||||
end
|
||||
|
||||
klass = Class.new do
|
||||
def read_attribute_for_serialization(name)
|
||||
{ :title => "New post!", :body => "First post body" }[name]
|
||||
end
|
||||
|
||||
def title
|
||||
read_attribute_for_serialization(:title)
|
||||
end
|
||||
|
||||
def body
|
||||
read_attribute_for_serialization(:body)
|
||||
end
|
||||
end
|
||||
|
||||
object = klass.new
|
||||
|
||||
actual = serializer.new(object, :root => :post).as_json
|
||||
|
||||
assert_equal({
|
||||
:post => {
|
||||
:title => "NEW POST!",
|
||||
:body => "First post body"
|
||||
}
|
||||
}, actual)
|
||||
end
|
||||
|
||||
def test_can_customize_attributes_with_read_attributes
|
||||
serializer = Class.new(ActiveModel::Serializer) do
|
||||
attributes :title, :body
|
||||
|
||||
def read_attribute_for_serialization(name)
|
||||
{ :title => "New post!", :body => "First post body" }[name]
|
||||
end
|
||||
end
|
||||
|
||||
actual = serializer.new(Object.new, :root => :post).as_json
|
||||
|
||||
assert_equal({
|
||||
:post => {
|
||||
:title => "New post!",
|
||||
:body => "First post body"
|
||||
}
|
||||
}, actual)
|
||||
end
|
||||
end
|
||||
|
||||
Reference in New Issue
Block a user