Class: Aspen::CustomGrammar::Grammar

Inherits:
Object
  • Object
show all
Defined in:
lib/aspen/custom_grammar/grammar.rb

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initializeGrammar

Returns a new instance of Grammar.



15
16
17
18
# File 'lib/aspen/custom_grammar/grammar.rb', line 15

def initialize()
  @registry = []
  @slug_counters = Hash.new { 1 }
end

Instance Attribute Details

#registryObject (readonly)

API Surface:

#add?
#match? (Boolean) -> Does the grammar cover this string, match this case?
#match  (Matcher) -> Request the matcher for this string.
#compile_pattern (Regexp) -> Given a matcher expression, return the Regexp pattern that can match against a string.


11
12
13
# File 'lib/aspen/custom_grammar/grammar.rb', line 11

def registry
  @registry
end

Instance Method Details

#add(maybe_matchers) ⇒ Object



44
45
46
47
48
# File 'lib/aspen/custom_grammar/grammar.rb', line 44

def add(maybe_matchers)
  matchers = Array(maybe_matchers).flatten
  raise unless matchers.all? { |m| m.is_a? Aspen::CustomGrammar::Matcher }
  matchers.each { |matcher| @registry << matcher }
end

#countObject



40
41
42
# File 'lib/aspen/custom_grammar/grammar.rb', line 40

def count
  registry.count
end

#inspectObject



36
37
38
# File 'lib/aspen/custom_grammar/grammar.rb', line 36

def inspect
  "#<Aspen::Grammar matchers: #{count}>"
end

#match(text) ⇒ Object Also known as: matcher_for



27
28
29
30
31
32
# File 'lib/aspen/custom_grammar/grammar.rb', line 27

def match(text)
  results = @registry.select { |m| m.match?(text) }
  warn "Found #{results.count} matches" if results.count > 1
  # raise Aspen::Error, "No results." if results.empty?
  return results.first
end

#match!(text) ⇒ Object



61
62
63
64
65
66
67
68
69
70
71
72
73
74
# File 'lib/aspen/custom_grammar/grammar.rb', line 61

def match!(text)
  unless match(text)
    raise Aspen::MatchError, <<~ERROR
      Couldn't find an Aspen grammar that matched the line:

          #{text}

      For more details (if you can), try running this to see all the match patterns:

          Aspen::Grammar.registry.map(&:pattern)

    ERROR
  end
end

#match?(string) ⇒ Boolean

Does the given text match a matcher?

Returns:

  • (Boolean)


21
22
23
24
25
# File 'lib/aspen/custom_grammar/grammar.rb', line 21

def match?(string)
  !!match(string)
rescue Aspen::Error
  false
end

#render(content) ⇒ Object

This doesn’t quite work, because var results is untyped.



51
52
53
54
55
# File 'lib/aspen/custom_grammar/grammar.rb', line 51

def render(content)
  matcher  = matcher_for(content)
  results  = results_for(content)
  template = matcher.template
end

#results_for(text) ⇒ Object



57
58
59
# File 'lib/aspen/custom_grammar/grammar.rb', line 57

def results_for(text)
  matcher_for(text).captures!(text)
end