Class: Chemicals::Template

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

Constant Summary collapse

NS =
'http://piesync.com/xml/chemicals'

Instance Method Summary collapse

Constructor Details

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

Returns a new instance of Template.



6
7
8
9
10
11
12
# File 'lib/chemicals/template.rb', line 6

def initialize(template, options = {})
  @template = Nokogiri::XML(template) { |c| c.noblanks }
  @options = {
    symbolize_keys: true
  }.merge!(options)
  @cache = {}
end

Instance Method Details

#add_namespaces(node) ⇒ Object

add the required namespaces to a node



64
65
66
67
68
# File 'lib/chemicals/template.rb', line 64

def add_namespaces node
  raw.root.namespace_definitions.each do |ns|
    node.add_namespace_definition ns.prefix, ns.href if ns.href != NS
  end
end

#for(path, namespaces = nil) ⇒ Object

get the configuration for an xpath expression



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

def for path, namespaces = nil
  @cache[path] ||= if namespaces
    for_node @template.at(canonicalize(path), namespaces)
  else
    for_node @template.at(canonicalize(path))
  end
end

#for_node(config_node) ⇒ Object

get the configuration for a config node



29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
# File 'lib/chemicals/template.rb', line 29

def for_node config_node
  # nil if no config node
  return nil unless config_node
  return nil if @template.at(canonicalize(config_node.path)).nil?
  # configuation is different in every case
  config = case config_node
    when Nokogiri::XML::Text
      config_node.content == '@' ? {} : {
        as: @options[:symbolize_keys] ? config_node.content.to_sym : config_node.content
      }
    when Nokogiri::XML::Attr
      {
        as: @options[:symbolize_keys] ? config_node.value.to_sym : config_node.value
      }
    when Nokogiri::XML::Element
      as = attribute(config_node, :as)
      {
        as: as ? (@options[:symbolize_keys] ? as.to_sym : as) : nil,
        mode: mode(config_node, as)
      }
  end
end

#mode(config_node, as) ⇒ Object



52
53
54
55
56
57
58
59
60
61
# File 'lib/chemicals/template.rb', line 52

def mode config_node, as
  mode = attribute(config_node, :mode)
  if mode
    mode.to_sym
  elsif as # only merge if we parse this node.
    :merge
  else
    nil
  end
end

#parse(source) ⇒ Object

parse a document



71
72
73
74
# File 'lib/chemicals/template.rb', line 71

def parse source
  @parser ||= Parser.new self
  @parser.parse source
end

#rawObject

returns the raw template



15
16
17
# File 'lib/chemicals/template.rb', line 15

def raw
  @template
end

#render(source) ⇒ Object

render a hash



77
78
79
80
# File 'lib/chemicals/template.rb', line 77

def render source
  @renderer ||= Renderer.new self
  @renderer.render source
end