Class: GTX

Inherits:
Object
  • Object
show all
Defined in:
lib/gtx.rb,
lib/gtx/version.rb

Constant Summary collapse

VERSION =
'0.1.1'

Instance Attribute Summary collapse

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(template, filename: nil) ⇒ GTX

Returns a new instance of GTX.



20
21
22
23
# File 'lib/gtx.rb', line 20

def initialize(template, filename: nil)
  @template = template
  @filename = filename
end

Instance Attribute Details

#filenameObject (readonly)

Returns the value of attribute filename.



18
19
20
# File 'lib/gtx.rb', line 18

def filename
  @filename
end

#templateObject (readonly)

Returns the value of attribute template.



18
19
20
# File 'lib/gtx.rb', line 18

def template
  @template
end

Class Method Details

.load_file(path, filename: nil) ⇒ Object



9
10
11
# File 'lib/gtx.rb', line 9

def load_file(path, filename: nil)
  new File.read(path), filename: filename || path
end

.render(template, context: nil, filename: nil) ⇒ Object



5
6
7
# File 'lib/gtx.rb', line 5

def render(template, context: nil, filename: nil)
  new(template, filename: filename).parse context
end

.render_file(path, context: nil, filename: nil) ⇒ Object



13
14
15
# File 'lib/gtx.rb', line 13

def render_file(path, context: nil, filename: nil)
  load_file(path, filename: filename).parse context
end

Instance Method Details

#erbObject



35
36
37
# File 'lib/gtx.rb', line 35

def erb
  ERB.new(erb_source, trim_mode: '-').tap { |a| a.filename = filename }
end

#erb_sourceObject



25
26
27
28
29
30
31
32
33
# File 'lib/gtx.rb', line 25

def erb_source
  template.strip.lines.map do |line|
    case line
    when /^\s*> ?(.*)/ then eval_vars $1
    when /^\s*= ?(.*)/ then "<%= #{eval_vars $1.strip} %>"
    else "<%- #{line.strip} -%>"
    end
  end.join "\n"
end

#parse(context = nil) ⇒ Object



39
40
41
42
43
# File 'lib/gtx.rb', line 39

def parse(context = nil)
  context ||= self
  context = context.instance_eval { binding } unless context.is_a? Binding
  erb.result context
end