Class: Serial::HashBuilder

Inherits:
Builder
  • Object
show all
Defined in:
lib/serial/hash_builder.rb

Overview

A builder for building hashes. You most likely just want to look at the public API methods in this class.

Instance Attribute Summary

Attributes inherited from Builder

#data

Instance Method Summary collapse

Methods inherited from Builder

build, #exec

Constructor Details

#initialize(context) ⇒ HashBuilder

This method is part of a private API. You should avoid using this method if possible, as it may be removed or be changed in the future.

Returns a new instance of HashBuilder.



6
7
8
9
# File 'lib/serial/hash_builder.rb', line 6

def initialize(context)
  @context = context
  @data = {}
end

Instance Method Details

#attribute(key, value = nil) {|builder, value| ... } ⇒ Object

Declare an attribute.

Examples:

without block

h.attribute(:id, 5) # => { "id" => 5 }

nested attribute, with block

h.attribute(:project, project) do |h, project|
  h.attribute(:name, project.name)
end # => { "project" => { "name" => … } }

Parameters:

  • key (#to_s)
  • value (defaults to: nil)

Yields:

  • (builder, value)

    declare nested attribute if block is given

Yield Parameters:

  • builder (HashBuilder)

    (keep in mind the examples shadow the outer h variable)

  • value


27
28
29
30
# File 'lib/serial/hash_builder.rb', line 27

def attribute(key, value = nil, &block)
  value = HashBuilder.build(@context, value, &block) if block
  @data[key.to_s] = value
end

#collection(key) {|builder| ... } ⇒ Object

Declare a collection attribute. This is a low-level method, see #map instead.

Examples:

h.collection(:people) do |l|
  l.element do |h|
    h.attribute(

Parameters:

  • key (#to_s)

Yield Parameters:

See Also:



53
54
55
# File 'lib/serial/hash_builder.rb', line 53

def collection(key, &block)
  attribute(key, ArrayBuilder.build(@context, &block))
end

#map(key, list) {|builder, value| ... } ⇒ Object

Declare a collection attribute from a list of values.

Examples:

h.map(:people, project.people) do |h, person|
  h.attribute(:name, person.name)
end # => { "people" => [{ "name" => … }] }

Parameters:

  • key (#to_s)
  • list (#each)

Yields:

  • (builder, value)

    yields each value from list to build an array of hashes

Yield Parameters:

See Also:



71
72
73
74
75
76
77
78
79
# File 'lib/serial/hash_builder.rb', line 71

def map(key, list, &block)
  collection(key) do |builder|
    list.each do |item|
      builder.element do |element|
        element.exec(item, &block)
      end
    end
  end
end