Module: Gon::Jbuilder

Defined in:
lib/gon/jbuilder.rb

Class Method Summary collapse

Class Method Details

.find_partials(lines = []) ⇒ Object



35
36
37
38
39
40
41
42
43
# File 'lib/gon/jbuilder.rb', line 35

def find_partials(lines = [])
  lines.map do |line|
    if line =~ /partial!/
      parse_partial(line)
    else
      line
    end
  end.flatten
end

.parse_jbuilder(jbuilder_path, controller) ⇒ Object



12
13
14
15
16
17
18
19
20
# File 'lib/gon/jbuilder.rb', line 12

def parse_jbuilder(jbuilder_path, controller)
  controller.instance_variables.each do |name|
    self.instance_variable_set(name, controller.instance_variable_get(name))
  end
  lines = find_partials(File.readlines(jbuilder_path))
  source = lines.join('')

  output = parse_source(source, controller)
end

.parse_partial(partial_line) ⇒ Object



22
23
24
25
26
27
28
29
30
31
32
33
# File 'lib/gon/jbuilder.rb', line 22

def parse_partial(partial_line)
  path = partial_line.match(/['"]([^'"]*)['"]/)[1]
  options_hash = partial_line.match(/,(.*)/)[1]
  if options_hash.present?
    options = eval '{' + options_hash + '}'
    options.each do |name, val|
      self.instance_variable_set('@' + name.to_s, val)
      eval "def #{name}; self.instance_variable_get('@' + '#{name.to_s}'); end"
    end
  end
  find_partials(File.readlines(path))
end

.parse_source(source, controller) ⇒ Object



5
6
7
8
9
10
# File 'lib/gon/jbuilder.rb', line 5

def parse_source(source, controller)
  output = ::JbuilderTemplate.encode(controller) do |json|
    eval source
  end
  JSON.parse(output)
end