Sha256: 81078e77a667957461be6806a7c969b30161ae2c1c72d1d42e9545cab7f46750

Contents?: true

Size: 784 Bytes

Versions: 10

Compression:

Stored size: 784 Bytes

Contents

module TurnipFormatter
  module Printer
    include ERB::Util

    #
    # @example
    #   render_template(:main, { name: 'user' })
    #     # => ERB.new('/path/to/main.erb') render { name: 'user' }
    #
    def render_template(name, params = {})
      render_template_list(name).result(template_params_binding(params))
    end

    private

    def render_template_list(name)
      if templates[name].nil?
        path = File.dirname(__FILE__) + "/template/#{name.to_s}.erb"
        templates[name] = ERB.new(File.read(path))
      end

      templates[name]
    end

    def template_params_binding(params)
      code = params.keys.map { |k| "#{k} = params[#{k.inspect}];" }.join
      eval(code + ";binding")
    end

    def templates
      @templates ||= {}
    end
  end
end

Version data entries

10 entries across 10 versions & 1 rubygems

Version Path
turnip_formatter-0.2.11 lib/turnip_formatter/printer.rb
turnip_formatter-0.2.10 lib/turnip_formatter/printer.rb
turnip_formatter-0.2.9 lib/turnip_formatter/printer.rb
turnip_formatter-0.2.8 lib/turnip_formatter/printer.rb
turnip_formatter-0.2.7 lib/turnip_formatter/printer.rb
turnip_formatter-0.2.6 lib/turnip_formatter/printer.rb
turnip_formatter-0.2.5 lib/turnip_formatter/printer.rb
turnip_formatter-0.2.4 lib/turnip_formatter/printer.rb
turnip_formatter-0.2.3 lib/turnip_formatter/printer.rb
turnip_formatter-0.2.2 lib/turnip_formatter/printer.rb