Sha256: 56afe8e898a5aec47ca54b3c8b151053df1462d4ef09eea892ef776dcd16235b

Contents?: true

Size: 1.4 KB

Versions: 1

Compression:

Stored size: 1.4 KB

Contents

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

class ErbComponent
  include ReqTools
  if defined? ActionView::Helpers::TagHelper
    include ActionView::Helpers::TagHelper
  end

  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)
    res = if parent
            parent.render.gsub("{{VIEW}}", str).gsub("{{view}}", str)
          else
            str
          end
    if res.respond_to? :html_safe
      res.html_safe
    else
      res
    end
  end

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

  def call
    self.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.2.1 lib/erb_component/erb_component.rb