Class: CollectionJSON::Builder

Inherits:
Object
  • Object
show all
Defined in:
lib/collection-json/builder.rb

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(collection) ⇒ Builder

Returns a new instance of Builder.



5
6
7
# File 'lib/collection-json/builder.rb', line 5

def initialize(collection)
  @collection = collection
end

Instance Attribute Details

#collectionObject (readonly)

Returns the value of attribute collection.



3
4
5
# File 'lib/collection-json/builder.rb', line 3

def collection
  @collection
end

Instance Method Details

#add_item(href, data = [], links = [], &block) ⇒ Object



25
26
27
28
29
30
31
32
33
# File 'lib/collection-json/builder.rb', line 25

def add_item(href, data = [], links = [], &block)
  href = CollectionJSON.add_host(href)
  collection.items << Item.from_hash({'href' => href}).tap do |item|
    item_builder = ItemBuilder.new(data, links)
    yield(item_builder) if block_given?
    item.merge!({'data' => item_builder.data}) if item_builder.data.length > 0
    item.merge!({'links' => item_builder.links}) if item_builder.links.length > 0
  end
end


17
18
19
20
21
22
23
# File 'lib/collection-json/builder.rb', line 17

def add_link(href, rel, opts = {})
  href = CollectionJSON.add_host(href)

  opts.select! {|k,v| VALID_LINK_ATTRIBUTES.include? k}
  opts.merge!({'rel' => rel, 'href' => href})
  collection.links << Link.from_hash(opts)
end

#add_query(href, rel, prompt = '', data = [], &block) ⇒ Object



35
36
37
38
39
40
41
42
43
# File 'lib/collection-json/builder.rb', line 35

def add_query(href, rel, prompt = '', data = [], &block)
  href = CollectionJSON.add_host(href)
  collection.queries << Query.from_hash({'href' => href, 'rel' => rel}).tap do |query|
    query_builder = QueryBuilder.new(data)
    yield(query_builder) if block_given?
    query.merge!({'prompt' => prompt}) if prompt != ''
    query.merge!({'data' => query_builder.data}) if query_builder.data.length > 0
  end
end

#set_code(code) ⇒ Object



13
14
15
# File 'lib/collection-json/builder.rb', line 13

def set_code(code)
  collection.code = code
end

#set_error(opts = {}) ⇒ Object



9
10
11
# File 'lib/collection-json/builder.rb', line 9

def set_error(opts = {})
  collection.error = opts
end

#set_template(data = [], &block) ⇒ Object



45
46
47
48
49
50
51
# File 'lib/collection-json/builder.rb', line 45

def set_template(data = [], &block)
  collection.template = Template.new.tap do |template|
    template_builder = TemplateBuilder.new(data)
    yield(template_builder) if block_given?
    template.merge!({'data' => template_builder.data}) if template_builder.data.length > 0
  end
end