Class: Squirm::Migrator::Template

Inherits:
Object
  • Object
show all
Defined in:
lib/squirm/migrator/template.rb

Overview

A class to easily create a binding for an Erb template, because I don’t like the def_class and def_method methods that ship with Erb. Not using an OpenStruct either because it uses an internal @table variable that makes it hard to deal with when our main template has a variable named “table.”

Instance Attribute Summary collapse

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(template, hash = {}) ⇒ Template

Returns a new instance of Template.



15
16
17
18
# File 'lib/squirm/migrator/template.rb', line 15

def initialize(template, hash = {})
  hash.each {|key, value| self[key] = value}
  @__template__ = template
end

Dynamic Method Handling

This class handles dynamic methods through the method_missing method

#method_missing(sym, *args, &block) ⇒ Object (private)



33
34
35
# File 'lib/squirm/migrator/template.rb', line 33

def method_missing(sym, *args, &block)
  sym =~ /=\z/ ? self[sym.to_s.gsub(/=\z/, '')] = args.first : self[sym]
end

Instance Attribute Details

#__template__Object (readonly)

Returns the value of attribute __template__.



13
14
15
# File 'lib/squirm/migrator/template.rb', line 13

def __template__
  @__template__
end

Class Method Details

.from_path(path, hash = {}) ⇒ Object



20
21
22
23
24
25
# File 'lib/squirm/migrator/template.rb', line 20

def self.from_path(path, hash = {})
  unless Pathname.new(path).absolute?
    path = File.expand_path(File.join("..", "templates", path), __FILE__)
  end
  new File.read(path), hash
end

Instance Method Details

#render(&block) ⇒ Object



27
28
29
# File 'lib/squirm/migrator/template.rb', line 27

def render(&block)
  ERB.new(__template__, nil, '-%>').result(binding)
end