Class: Psychic::RegexpTokenHandler

Inherits:
Object
  • Object
show all
Defined in:
lib/psychic/tokens.rb

Instance Method Summary collapse

Constructor Details

#initialize(template, token_pattern, token_replacement) ⇒ RegexpTokenHandler

Returns a new instance of RegexpTokenHandler.



5
6
7
8
9
# File 'lib/psychic/tokens.rb', line 5

def initialize(template, token_pattern, token_replacement)
  @template = template
  @token_pattern = token_pattern
  @token_replacement = token_replacement
end

Instance Method Details

#render(variables = {}) ⇒ Object



15
16
17
18
19
20
21
22
23
# File 'lib/psychic/tokens.rb', line 15

def render(variables = {})
  @template.gsub(@token_pattern) do
    full_match = Regexp.last_match[0]
    key = Regexp.last_match[1]
    value = variables[key]
    value = @token_replacement.gsub('\\1', value.to_s) unless @token_replacement.nil?
    full_match.gsub(@token_pattern, value)
  end
end

#tokensObject



11
12
13
# File 'lib/psychic/tokens.rb', line 11

def tokens
  @template.scan(@token_pattern).flatten.uniq
end