class Molder::Renderer

== 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)
   ⤷ #<Molder::Renderer:0x007fb90b9c32d8>
   content = '{{ salutation }}, please attend my birthday. Sincerely, {{ from }}.'
   ⤷ {{ salutation }}, please attend my birthday. Sincerely, {{ from }}.
   @Renderer.render(content)
    ⤷ "Dear Adam & Eve, please attend my birthday. Sincerely, Jesus."

== Troubleshooting

See errors documented under this class.

Constants

MAX_RECURSIONS

Attributes

render_opts[RW]
template[RW]

Public Class Methods

new(template_string, options = {}) click to toggle source

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

# 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

Public Instance Methods

render(params) click to toggle source

Render given content using expanded params.

# 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

Private Instance Methods

expand_arguments(params) click to toggle source
# File lib/molder/renderer.rb, line 94
def expand_arguments(params)
  current    = YAML.dump(params)
  recursions = 0

  while current =~ %r[{{\s*[a-z_]+\s*}}]
    recursions += 1
    raise TooManyRecursionsError.new if recursions > MAX_RECURSIONS
    previous = current
    current  = ::Liquid::Template.parse(previous).render(params)
  end

  begin
    Hashie::Mash.new(YAML.load(current))
  rescue Psych::SyntaxError => e
    STDERR.puts "Error parsing YAML Renderer:\n" +
                  e.message.red +
                  "\n#{current}"
    raise SyntaxError.new(e)
  end
end