Class: Kotoshu::Grammar::RuleEngine

Inherits:
Object
  • Object
show all
Defined in:
lib/kotoshu/grammar/rule_engine.rb

Overview

Engine for loading and executing grammar rules from YAML configuration.

This implements configuration-driven design where all linguistic data (rules, patterns, exceptions) is stored in YAML files, not hardcoded.

Examples:

Loading rules for English

engine = RuleEngine.new(language: 'en')
errors = engine.check(tokens)

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(language:, rules_path: nil, dictionaries_path: nil) ⇒ RuleEngine

Create a new rule engine for a language.

Parameters:

  • language (String)

    Language code (e.g., ‘en’, ‘de’, ‘fr’)

  • rules_path (String, nil) (defaults to: nil)

    Optional custom path to grammar rules

  • dictionaries_path (String, nil) (defaults to: nil)

    Optional custom path to dictionaries directory



25
26
27
28
29
30
# File 'lib/kotoshu/grammar/rule_engine.rb', line 25

def initialize(language:, rules_path: nil, dictionaries_path: nil)
  @language = language
  @rules_path = rules_path || default_rules_path(dictionaries_path)
  @loader = RuleLoader.new(@rules_path)
  @rules = @loader.load_rules
end

Instance Attribute Details

#languageObject (readonly)

Returns the value of attribute language.



18
19
20
# File 'lib/kotoshu/grammar/rule_engine.rb', line 18

def language
  @language
end

#rulesObject (readonly)

Returns the value of attribute rules.



18
19
20
# File 'lib/kotoshu/grammar/rule_engine.rb', line 18

def rules
  @rules
end

Instance Method Details

#check(tokens) ⇒ Array<Hash>

Check tokens against all loaded rules.

Parameters:

  • tokens (Array<Hash>)

    Array of token hashes with :token, :pos_tag, :position keys

Returns:

  • (Array<Hash>)

    Array of error hashes



36
37
38
39
40
41
42
43
# File 'lib/kotoshu/grammar/rule_engine.rb', line 36

def check(tokens)
  errors = []
  @rules.each do |rule|
    rule_errors = rule.check(tokens)
    errors.concat(rule_errors)
  end
  errors
end

#get_rule(id) ⇒ Rule?

Get a specific rule by ID.

Parameters:

  • id (String)

    Rule ID

Returns:

  • (Rule, nil)

    The rule if found, nil otherwise



56
57
58
# File 'lib/kotoshu/grammar/rule_engine.rb', line 56

def get_rule(id)
  @rules.find { |r| r.id == id }
end

#rule_exists?(id) ⇒ Boolean

Check if a rule exists.

Parameters:

  • id (String)

    Rule ID

Returns:

  • (Boolean)

    True if rule exists



64
65
66
# File 'lib/kotoshu/grammar/rule_engine.rb', line 64

def rule_exists?(id)
  @rules.any? { |r| r.id == id }
end

#rule_namesArray<String>

Get list of rule IDs.

Returns:

  • (Array<String>)

    Array of rule IDs



48
49
50
# File 'lib/kotoshu/grammar/rule_engine.rb', line 48

def rule_names
  @rules.map(&:id)
end