Sha256: dc78a2159355ab682228192bb932581c79ba0965afdc43a2fa49bc73e70d4e89

Contents?: true

Size: 1.16 KB

Versions: 1

Compression:

Stored size: 1.16 KB

Contents

require "erb_component/version"
require "erb_component/req_tools"
require 'erb'

class ErbComponent
  include ReqTools

  class Error < StandardError;
  end

  attr_reader :req, :parent

  def initialize(req, opts = {})
    @req = req
    @template = opts[:template]
    begin
      @parent = self.class.superclass == ErbComponent ? nil : self.class.superclass.new(req)
      if @parent && !(parent.template['{{VIEW}}'] || parent.template['{{view}}'])
        @parent = parent.parent
      end
    rescue ArgumentError
    end
  end

  def render
    str = ERB.new(template).result(binding)
    if parent
      parent.render.gsub("{{VIEW}}", str).gsub("{{view}}", str)
    else
      str
    end
  end

  def self.render(opts = {})
    new(opts).render
  end

  def self.call(req, opts = {})
    new(req, opts).render
  end

  def self.current_file=(file)
    @current_file = file
  end

  def self.current_file
    @current_file
  end

  def template_file_path
    self.class.current_file.gsub('.rb', '.erb')
  end

  def template
    return @template if @template
    return File.read(template_file_path) if template_file_path
    fail "not found: #{template_file_path}"
  end
end

Version data entries

1 entries across 1 versions & 1 rubygems

Version Path
erb_component-0.1.9 lib/erb_component/erb_component.rb