Class: HashBuilder::Template

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

Overview

Renders templates with ‘.json_builder’ extension.

If the template is a normal view, it will render a JSON string. If the template however is a partial, it renders a Hash so that json_builder files can use partials.

Class Method Summary collapse

Class Method Details

.call(template) ⇒ Object



12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
# File 'lib/hash_builder/template.rb', line 12

def self.call (template)
  # The template is on the first line, so that line numbers in the
  # error stacks are correct.
  render_code = <<-RUBY
hash = HashBuilder.build(scope: self, locals: local_assigns) do #{template.source} end

if hash.size == 1 && hash.keys == [:array]
  hash = hash[:array]
end


RUBY

  if !is_partial?(template)
    # ActiveModel defines #as_json in a way, that is not compatible
    # with JSON.
    if defined?(ActiveModel)
      render_code += "ActiveSupport::JSON.encode(hash)"
    else
      render_code += "JSON.generate(hash)"
    end
  else
    render_code += "hash"
  end
  
  render_code
end

.default_formatObject



8
9
10
# File 'lib/hash_builder/template.rb', line 8

def self.default_format
  Mime::JSON
end

.is_partial?(template) ⇒ Boolean

Returns:

  • (Boolean)


40
41
42
# File 'lib/hash_builder/template.rb', line 40

def self.is_partial? (template)
  template.virtual_path.split("/").last.start_with?("_")
end