Class: Nm::Template

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

Instance Method Summary collapse

Constructor Details

#initialize(*args) ⇒ Template

Returns a new instance of Template.



8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
# File 'lib/nm/template.rb', line 8

def initialize(*args)
  @__dstack__ = [ nil ]

  # apply any given locals to template scope as methods
  metaclass = class << self; self; end
  (args.last.kind_of?(::Hash) ? args.pop : {}).each do |key, value|
    metaclass.class_eval{ define_method(key){ value } }
  end

  source_file = args.last.kind_of?(::String) ? args.pop : ''
  @__source__ = args.last.kind_of?(Source) ? args.pop : DefaultSource.new

  return if source_file.empty?

  unless File.exists?(source_file)
    raise ArgumentError, "source file `#{source_file}` does not exist"
  end
  instance_eval(@__source__.data(source_file), source_file, 1)
end

Instance Method Details

#__data__Object



28
29
30
# File 'lib/nm/template.rb', line 28

def __data__
  @__dstack__.last
end

#__map__(list, &block) ⇒ Object Also known as: map, _map, m



49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
# File 'lib/nm/template.rb', line 49

def __map__(list, &block)
  unless list.respond_to?(:map)
    raise ArgumentError, "given list (`#{list.class}`) doesn't respond to `.map`"
  end
  unless @__dstack__[-1].nil? || @__dstack__[-1].is_a?(::Array)
    raise Nm::InvalidError, "invalid `map` call"
  end
  @__dstack__[-1] ||= ::Array.new

  list.map do |item|
    @__dstack__.push(nil)
    self.instance_exec(item, &(block || Proc.new {}))
    @__dstack__.pop.tap{ |v| @__dstack__[-1].push(v || item) }
  end

  return self
end

#__node__(key, value = nil, &block) ⇒ Object Also known as: node, _node, n



32
33
34
35
36
37
38
39
40
41
42
43
# File 'lib/nm/template.rb', line 32

def __node__(key, value = nil, &block)
  unless @__dstack__[-1].nil? || @__dstack__[-1].is_a?(::Hash)
    raise Nm::InvalidError, "invalid `node` call"
  end
  @__dstack__[-1] ||= ::Hash.new

  @__dstack__.push(nil)
  self.instance_exec(&(block || Proc.new {}))
  @__dstack__.pop.tap{ |v| @__dstack__[-1][key] = (v || value) }

  return self
end

#__partial__(*args) ⇒ Object Also known as: partial, _partial, p



82
83
84
85
86
87
# File 'lib/nm/template.rb', line 82

def __partial__(*args)
  data = @__source__.partial(*args)
  @__dstack__[-1] = @__dstack__[-1].__nm_add_call_data__('partial', data)

  return self
end

#__render__(*args) ⇒ Object Also known as: render, _render, r



71
72
73
74
75
76
# File 'lib/nm/template.rb', line 71

def __render__(*args)
  data = @__source__.render(*args)
  @__dstack__[-1] = @__dstack__[-1].__nm_add_call_data__('render', data)

  return self
end