Class: Molder::Renderer

Inherits:
Object
  • Object
show all
Defined in:
lib/molder/renderer.rb

Overview

Usage

Generally you first generate a set of parameters (a nested hash) that represents configuration of your application. As was mentioned above, the parameter hash can be self-referential – it will be automatically expanded.

Once you create a Renderer instance with a given parameter set, you can then use the #render method to convert content with Renderer placeholers into a fully resolved string.

Example

/

require 'molder/renderer'

params = { 'invitee' => 'Adam',
             'extra' => 'Eve',
        'salutation' => 'Dear {{ invitee }} & {{ extra }}',
             'from'  => 'Jesus'
}
@Renderer = ::Molder::Renderer.new(params)

Troubleshooting

See errors documented under this class.

Defined Under Namespace

Classes: SyntaxError, TooManyRecursionsError, UnresolvedReferenceError

Constant Summary collapse

MAX_RECURSIONS =
100

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(template_string, options = {}) ⇒ Renderer

Create Renderer object, while storing and auto-expanding params.



69
70
71
72
73
74
75
76
# File 'lib/molder/renderer.rb', line 69

def initialize(template_string, options = {})
  self.template    = template_string
  self.render_opts = if options[:blank]
                       {}
                     else
                       { strict_variables: true }
                     end
end

Instance Attribute Details

#render_optsObject

Returns the value of attribute render_opts.



66
67
68
# File 'lib/molder/renderer.rb', line 66

def render_opts
  @render_opts
end

#templateObject

Returns the value of attribute template.



66
67
68
# File 'lib/molder/renderer.rb', line 66

def template
  @template
end

Instance Method Details

#render(params) ⇒ Object

Render given content using expanded params.



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

def render(params)
  attributes      = expand_arguments(Hashie.stringify_keys(params.to_h))
  liquid_template = Liquid::Template.parse(template)

  liquid_template.render(attributes, **render_opts).tap do
    unless liquid_template.errors.empty?
      raise LiquidTemplateError, "#{liquid_template.errors.map(&:message).join("\n")}"
    end
  end.gsub(/\n/, ' ').gsub(/\s{2,}/, ' ').strip
rescue ArgumentError => e
  raise UnresolvedReferenceError.new(e)
end