Top Level Namespace

Defined Under Namespace

Modules: AttributeSerializer

Instance Method Summary collapse

Instance Method Details

#AttributeSerializer(*args, &blk) ⇒ Object

Public: Define a serializer or serialize an object or collection

Examples

Define a default serializer on your class:

AttributeSerializer BlogPost, %w(id created_at title body) do
  def body
    Rdiscount.new(formateee.body).to_html
  end
end

Then serialize and instance like:

AttributeSerializer @post

You can also define other serializers:

AttributeSerializer BlogPost, :summary, %w(id created_at title)

And serialize collections:

AttributeSerializer @posts, :summary

AttributeSerializer returns an OrderedHash as the serialization, it’s up to you to call #to_json or #to_yaml on that object

Returns an OrderedHash serialization when given an object or collection



96
97
98
99
100
101
102
103
# File 'lib/attribute_serializer.rb', line 96

def AttributeSerializer(*args, &blk)
  if args.first.is_a?(Class)
    klass, context_name, attribs = (args.size == 3) ? args : [args[0], :default, args[1]]
    AttributeSerializer.add_context_set klass, context_name, attribs, &blk
  else
    AttributeSerializer.generate(args[1] || :default, args[0])
  end
end