Module: ApiBuilder::Renderer

Defined in:
lib/api_builder/renderer.rb

Instance Method Summary collapse

Dynamic Method Handling

This class handles dynamic methods through the method_missing method

#method_missing(name, *args, &block) ⇒ Object



7
8
9
10
11
12
13
14
15
16
17
18
19
# File 'lib/api_builder/renderer.rb', line 7

def method_missing(name, *args, &block)
  @_out = {} if @_out.nil?

  if block_given?
    out = @_out
    @_out = {}
    block.call
    out[name] = @_out
    @_out = out
  else
    @_out[name] = args[0]
  end
end

Instance Method Details

#array(name, value = nil, &block) ⇒ Object



21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
# File 'lib/api_builder/renderer.rb', line 21

def array(name, value = nil, &block)
  if @_out.nil?
    @_out = ArrayWithName.new(name)
    block.call
  elsif @_out.is_a?(Array)
    out = @_out
    @_out = ArrayWithName.new(name)
    block.call
    out << @_out
    @_out = out
  else # out is a hash
    out = @_out
    @_out = []
    block.call
    out[name] = @_out
    @_out = out
  end
end

#element(name, value = nil, &block) ⇒ Object



40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
# File 'lib/api_builder/renderer.rb', line 40

def element(name, value = nil, &block)
  if block_given?
    if @_out.nil?
      @_out = HashWithName.new(name)
      block.call
    elsif @_out.is_a?(Array)
      out = @_out
      @_out = HashWithName.new(name)
      block.call
      out << @_out
      @_out = out
    else # out is a hash
      out = @_out
      @_out = {}
      block.call
      out[name] = @_out
      @_out = out
    end
  elsif name.is_a?(Hash)
    if @_out.nil?
      @_out = StringWithName.new(name.keys[0], name.values[0])
    elsif @_out.is_a?(Array)
      @_out << StringWithName.new(name.keys[0], name.values[0])
    else # out is a hash
      @_out[name.keys[0]] = name.values[0]
    end
  else
    if @_out.nil?
      @_out = StringWithName.new(name, value)
    elsif @_out.is_a?(Array)
      @_out << StringWithName.new(name, value)
    else # out is a hash
      @_out[name] = value
    end
  end
end

#get_outputObject



77
78
79
80
81
82
83
84
85
86
87
88
89
90
# File 'lib/api_builder/renderer.rb', line 77

def get_output
  case params[:format].to_sym
  when :json
    if params[:callback]
      "#{params[:callback]}(#{@_out.to_json})"
    else
      @_out.to_json
    end
  when :xml
    @_out.to_xml
  else
    raise "unknown format '#{params[:format]}'"
  end
end

#id(*args, &block) ⇒ Object



3
4
5
# File 'lib/api_builder/renderer.rb', line 3

def id(*args, &block)
  method_missing(:id, *args, &block)
end