Class: Hpreserve::Variables

Inherits:
Object
  • Object
show all
Defined in:
lib/hpreserve/variables.rb

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(vars = {}) ⇒ Variables

Returns a new instance of Variables.



7
8
9
# File 'lib/hpreserve/variables.rb', line 7

def initialize(vars={})
  self.storage = vars
end

Instance Attribute Details

#storageObject

Returns the value of attribute storage.



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

def storage
  @storage
end

Instance Method Details

#[](*path) ⇒ Object

climbs the branches of the variable hash’s tree, handling non-hashes along the way.



12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
# File 'lib/hpreserve/variables.rb', line 12

def [](*path)
  path = path.flatten
  return '' if path.empty?
  stack = @storage
  path.each do |piece|
    # much of this stolen blatantly from liquid
    if (stack.respond_to?(:has_key?) and stack.has_key?(piece)) ||
       (stack.respond_to?(:fetch) and piece =~ /^\d+$/)
      piece = piece.to_i if piece =~ /^\d+$/
      stack[piece] = stack[piece].to_hpreserve if stack[piece].respond_to?(:to_hpreserve)
      stack = stack[piece]
    elsif %w(first last size).include?(piece) and stack.respond_to?(piece)
      item = stack.send(piece)
      stack = item.respond_to?(:to_hpreserve) ? item.to_hpreserve : item
    else
      return nil
    end
  end
  stack
end

#substitute(str = '') ⇒ Object



33
34
35
36
37
38
# File 'lib/hpreserve/variables.rb', line 33

def substitute(str='')
  str.gsub(/\{([\w\.]+)[\s\|]*([^\{\}]+)?\}/) do |m|
    val, default = $1, $2
    self["#{val}".split('.')] || "#{default}";
  end
end