Class: Freud::Variables

Inherits:
Object
  • Object
show all
Includes:
Agrippa::MutableHash
Defined in:
lib/freud/variables.rb

Constant Summary collapse

VARIABLES =
/(?<!\\)%((\w+)|{(\w+)}|{(\w+)\|(.*)})/i
ESCAPED_SIGILS =
/\\%/
UNDEFINED =
Object.new

Instance Method Summary collapse

Constructor Details

#initialize(*args) ⇒ Variables



13
14
15
16
# File 'lib/freud/variables.rb', line 13

def initialize(*args)
    super
    @stack = {}
end

Instance Method Details

#apply(input) ⇒ Object



36
37
38
39
40
41
42
43
44
45
46
47
# File 'lib/freud/variables.rb', line 36

def apply(input)
    return(nil) if input.nil?
    interpolated = input.gsub(VARIABLES) do 
        key = $~[2] || $~[3] || $~[4] 
        default = $~[5] || UNDEFINED
        push_stack(key, input)
        output = apply(fetch(key, default).to_s)
        pop_stack(key)
        output
    end
    interpolated.gsub(ESCAPED_SIGILS, "%")
end

#each_pair(&block) ⇒ Object



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

def each_pair(&block)
    @state.each_pair(&block)
end

#fetch(key, default = UNDEFINED) ⇒ Object



30
31
32
33
34
# File 'lib/freud/variables.rb', line 30

def fetch(key, default = UNDEFINED)
    key = key.to_sym
    return(@state.fetch(key, default)) unless (default == UNDEFINED)
    @state.fetch(key) { raise(KeyError, "Unknown variable: #{key}") }
end

#merge(updates) ⇒ Object



26
27
28
# File 'lib/freud/variables.rb', line 26

def merge(updates)
    chain(updates)
end

#pop_stack(key) ⇒ Object



59
60
61
62
# File 'lib/freud/variables.rb', line 59

def pop_stack(key)
    @stack.delete(key)
    self
end

#push_stack(key, input) ⇒ Object



49
50
51
52
53
54
55
56
57
# File 'lib/freud/variables.rb', line 49

def push_stack(key, input)
    if @stack[key]
        message = "Infinite loop evaluating '%#{key}' in '#{input}'"
        raise(RuntimeError, message)
    else
        @stack[key] = true
        self
    end
end

#test(input) ⇒ Object



22
23
24
# File 'lib/freud/variables.rb', line 22

def test(input)
    (input =~ VARIABLES) ? true : false
end