Class: Semr::Phrase

Inherits:
Object
  • Object
show all
Defined in:
lib/semr/phrase.rb

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(all_concepts, phrase, &block) ⇒ Phrase

^ matches phrase from beginning, should we use $ regex = Regexp.new(phrase, Regexp::IGNORECASE) <- fall back when oniguruma not installed



8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
# File 'lib/semr/phrase.rb', line 8

def initialize(all_concepts, phrase, &block)
  refined_phrase = remove_optional_words(phrase)
  phrase.symbols.each do |symbol|
    if all_concepts[symbol].nil?
      raise InvalidConceptError.new("Unable to create phrase because :#{symbol} concept has not been defined.")  
    else
      concept = all_concepts[symbol]
      concepts << concept
      concept_matcher = "(?<#{symbol}>#{concept.definition.to_regexp})"
      refined_phrase = refined_phrase.gsub(":#{symbol}", concept_matcher)
    end
  end
  @original = "^#{refined_phrase}"
  @regex, @block = Oniguruma::ORegexp.new(@original, :options => Oniguruma::OPTION_IGNORECASE), block      
end

Instance Attribute Details

#blockObject (readonly)

Returns the value of attribute block.



4
5
6
# File 'lib/semr/phrase.rb', line 4

def block
  @block
end

#regexObject (readonly)

Returns the value of attribute regex.



4
5
6
# File 'lib/semr/phrase.rb', line 4

def regex
  @regex
end

Instance Method Details

#conceptsObject



24
25
26
# File 'lib/semr/phrase.rb', line 24

def concepts
  @concepts ||= []
end

#debug(match) ⇒ Object



49
50
51
52
53
54
55
# File 'lib/semr/phrase.rb', line 49

def debug(match)
  matches = match[0..match.end]
  matches.each do |match|
    puts match
    puts ' ---- '
  end
end

#handles?(statement) ⇒ Boolean

Returns:

  • (Boolean)


32
33
34
35
# File 'lib/semr/phrase.rb', line 32

def handles?(statement)
  match = regex.match(statement) 
  !match.nil?
end

#interpret(statement, translation) ⇒ Object



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

def interpret(statement, translation)
  args = []
  regex.scan(statement) do |match|
    @concepts.each do |concept|
      actual_match = match[concept.name]
      args << concept.normalize(actual_match)
    end
  end
  # args = args.first if args.size == 1
  translation.instance_exec(*args, &block)
end

#remove_optional_words(phrase) ⇒ Object



28
29
30
# File 'lib/semr/phrase.rb', line 28

def remove_optional_words(phrase)
  phrase.gsub(/\<([\w]*)\>\s?/, '(?:\1)?\s?')
end

#to_regexpObject



57
58
59
# File 'lib/semr/phrase.rb', line 57

def to_regexp
  "(#{@original})"
end