Class: Serialism::Serializer
- Inherits:
-
Object
- Object
- Serialism::Serializer
- Defined in:
- lib/serialism/serializer.rb
Overview
Base class for concrete serializers to inherit from.
Example:
class Foo
attr_accessor :id
end
class FooSerializer < Serialism::Serializer
attributes :id, :computed
def computed
"computed - #{object.id}"
end
end
item = Foo.new
item.id = 12
serializer = FooSerializer.new(item)
serializer.render
# => {id: 12, computed: "computed - 12"}
Instance Attribute Summary collapse
-
#object ⇒ Object
readonly
Returns the value of attribute object.
Class Method Summary collapse
Instance Method Summary collapse
-
#initialize(object) ⇒ Serializer
constructor
A new instance of Serializer.
-
#render ⇒ Hash
Transform ‘object` using rules defined by the serializer.
Constructor Details
#initialize(object) ⇒ Serializer
Returns a new instance of Serializer.
33 34 35 |
# File 'lib/serialism/serializer.rb', line 33 def initialize(object) @object = object end |
Instance Attribute Details
#object ⇒ Object (readonly)
Returns the value of attribute object.
25 26 27 |
# File 'lib/serialism/serializer.rb', line 25 def object @object end |
Class Method Details
.attributes(*attrs) ⇒ Object
28 29 30 31 |
# File 'lib/serialism/serializer.rb', line 28 def self.attributes(*attrs) @attributes = attrs if !attrs.empty? @attributes end |
Instance Method Details
#render ⇒ Hash
Transform ‘object` using rules defined by the serializer.
40 41 42 43 44 45 46 47 48 49 50 51 |
# File 'lib/serialism/serializer.rb', line 40 def render self.class.attributes.inject({}) do |memo, attr| if respond_to?(attr) memo[attr] = send(attr) elsif object.respond_to?(attr) memo[attr] = object.send(attr) else raise ArgumentError, "Unknown attribute :#{attr}" end memo end end |