mirror of
https://github.com/ditkrg/active_model_serializers.git
synced 2026-01-23 06:16:50 +00:00
Serialize just attributes
This commit is contained in:
parent
14f51f2ea9
commit
7143eb8301
43
lib/active_model/serializer.rb
Normal file
43
lib/active_model/serializer.rb
Normal file
@ -0,0 +1,43 @@
|
||||
module ActiveModel
|
||||
class Serializer
|
||||
class << self
|
||||
def inherited(base)
|
||||
base._attributes = {}
|
||||
end
|
||||
|
||||
attr_accessor :_attributes
|
||||
|
||||
def attributes(*attrs)
|
||||
@_attributes = attrs.map(&:to_s)
|
||||
|
||||
attrs.each do |attr|
|
||||
define_method attr do
|
||||
object.read_attribute_for_serialization(attr)
|
||||
end
|
||||
end
|
||||
end
|
||||
end
|
||||
|
||||
def initialize(object)
|
||||
@object = object
|
||||
end
|
||||
attr_accessor :object
|
||||
|
||||
alias read_attribute_for_serialization send
|
||||
|
||||
def attributes
|
||||
self.class._attributes.each_with_object({}) do |name, hash|
|
||||
hash[name] = send(name)
|
||||
end
|
||||
end
|
||||
|
||||
def serializable_hash(options={})
|
||||
return nil if object.nil?
|
||||
attributes
|
||||
end
|
||||
|
||||
def as_json(options={})
|
||||
serializable_hash
|
||||
end
|
||||
end
|
||||
end
|
||||
44
test/serializer/attributes_test.rb
Normal file
44
test/serializer/attributes_test.rb
Normal file
@ -0,0 +1,44 @@
|
||||
require 'newbase/test_helper'
|
||||
require 'newbase/active_model/serializer'
|
||||
|
||||
module SerializerTest
|
||||
module Attributes
|
||||
class Model
|
||||
def initialize(hash={})
|
||||
@attributes = hash
|
||||
end
|
||||
|
||||
def read_attribute_for_serialization(name)
|
||||
@attributes[name]
|
||||
end
|
||||
end
|
||||
|
||||
class ModelSerializer < ActiveModel::Serializer
|
||||
attributes :attr1, :attr2
|
||||
end
|
||||
|
||||
class Test < ActiveModel::TestCase
|
||||
def setup
|
||||
model = Model.new({ :attr1 => 'value1', :attr2 => 'value2', :attr3 => 'value3' })
|
||||
@model_serializer = ModelSerializer.new(model)
|
||||
end
|
||||
|
||||
def test_attributes_definition
|
||||
assert_equal(['attr1', 'attr2'],
|
||||
@model_serializer.class._attributes)
|
||||
end
|
||||
|
||||
def test_attributes_serialization_using_serializable_hash
|
||||
assert_equal({
|
||||
'attr1' => 'value1', 'attr2' => 'value2'
|
||||
}, @model_serializer.serializable_hash)
|
||||
end
|
||||
|
||||
def test_attributes_serialization_using_as_json
|
||||
assert_equal({
|
||||
'attr1' => 'value1', 'attr2' => 'value2'
|
||||
}, @model_serializer.as_json)
|
||||
end
|
||||
end
|
||||
end
|
||||
end
|
||||
5
test/test_helper.rb
Normal file
5
test/test_helper.rb
Normal file
@ -0,0 +1,5 @@
|
||||
ENV['RAILS_ENV'] = 'test'
|
||||
|
||||
require 'bundler/setup'
|
||||
require 'rails'
|
||||
require 'rails/test_help'
|
||||
Loading…
Reference in New Issue
Block a user