Class: Turnip::Placeholder

Inherits:
Object
  • Object
show all
Defined in:
lib/turnip/placeholder.rb

Defined Under Namespace

Classes: Match

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(name, &block) ⇒ Placeholder

Returns a new instance of Placeholder.



42
43
44
45
46
47
# File 'lib/turnip/placeholder.rb', line 42

def initialize(name, &block)
  @name = name
  @matches = []
  @default = nil
  instance_eval(&block)
end

Class Method Details

.add(name, &block) ⇒ Object



6
7
8
9
10
11
12
13
# File 'lib/turnip/placeholder.rb', line 6

def add(name, &block)
  if placeholders.key?(name)
    location = caller_locations.detect { |l| l.to_s !~ /lib\/turnip\/dsl\.rb/ }
    warn "Placeholder :#{name} was replaced at #{location}."
  end

  placeholders[name] = Placeholder.new(name, &block)
end

.apply(name, value) ⇒ Object



19
20
21
# File 'lib/turnip/placeholder.rb', line 19

def apply(name, value)
  find(name).apply(value)
end

.find(name) ⇒ Object



23
24
25
# File 'lib/turnip/placeholder.rb', line 23

def find(name)
  placeholders[name] or default
end

.resolve(name) ⇒ Object



15
16
17
# File 'lib/turnip/placeholder.rb', line 15

def resolve(name)
  find(name).regexp
end

Instance Method Details

#apply(value) ⇒ Object



49
50
51
52
# File 'lib/turnip/placeholder.rb', line 49

def apply(value)
  match, params = find_match(value)
  if match and match.block then match.block.call(*params) else value end
end

#default(&block) ⇒ Object



58
59
60
61
62
63
# File 'lib/turnip/placeholder.rb', line 58

def default(&block)
  @default ||= Match.new(
    %r{['"]?((?:(?<=")[^"]*)(?=")|(?:(?<=')[^']*(?='))|(?<!['"])[[:alnum:]_-]+(?!['"]))['"]?},
    block
  )
end

#match(regexp, &block) ⇒ Object



54
55
56
# File 'lib/turnip/placeholder.rb', line 54

def match(regexp, &block)
  @matches << Match.new(regexp, block)
end

#regexpObject



65
66
67
# File 'lib/turnip/placeholder.rb', line 65

def regexp
  Regexp.new(placeholder_matches.map(&:regexp).join('|'))
end