Class: Ruleby::Core::Engine

Inherits:
Object
  • Object
show all
Defined in:
lib/core/engine.rb

Overview

This is the core class of the library. A new rule engine is created by instantiating it. Each rule engine has one inference engine, one rule set and one working memory.

Instance Method Summary collapse

Constructor Details

#initialize(wm = WorkingMemory.new, cr = RulebyConflictResolver.new) ⇒ Engine

Returns a new instance of Engine.



186
187
188
189
190
191
192
# File 'lib/core/engine.rb', line 186

def initialize(wm=WorkingMemory.new,cr=RulebyConflictResolver.new)
  @root = nil
  @working_memory = wm
  @conflict_resolver = cr
  @wm_altered = false
  assert InitialFact.new
end

Instance Method Details

#assert(object, &block) ⇒ Object

This method id called to add a new fact to working memory



199
200
201
202
# File 'lib/core/engine.rb', line 199

def assert(object,&block)
  @wm_altered = true
  fact_helper(object,:plus,&block)
end

#assert_rule(rule) ⇒ Object

This method adds a new rule to the system.



222
223
224
225
226
227
228
# File 'lib/core/engine.rb', line 222

def assert_rule(rule)         
  if @root == nil
    @root = RootNode.new(@working_memory) 
    @root.reset_counter
  end
  @root.assert_rule rule
end

#factsObject



194
195
196
# File 'lib/core/engine.rb', line 194

def facts
  @working_memory.facts.collect{|f| f.object}
end

#match(agenda = nil, used_agenda = []) ⇒ Object

This method executes the activations that were generated by the rules that match facts in working memory.



232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
# File 'lib/core/engine.rb', line 232

def match(agenda=nil, used_agenda=[])      
  if @root
    @root.reset_counter
    agenda = @root.matches unless agenda 
    while (agenda.length > 0)
      agenda = @conflict_resolver.resolve agenda            
      activation = agenda.pop   
      used_agenda.push activation     
      activation.fire self   
      if @wm_altered          
        agenda = @root.matches(false)    
        @root.increment_counter
        @wm_altered = false
      end
    end
  end
end

#modify(object, &block) ⇒ Object

This method is called to alter an existing fact. It is essentially a retract followed by an assert.



212
213
214
215
# File 'lib/core/engine.rb', line 212

def modify(object,&block)
  retract(object,&block)
  assert(object,&block)
end


250
251
252
253
# File 'lib/core/engine.rb', line 250

def print
  @working_memory.print
  @root.print
end

#retract(object, &block) ⇒ Object

This method is called to remove an existing fact from working memory



205
206
207
208
# File 'lib/core/engine.rb', line 205

def retract(object,&block)
  @wm_altered = true
  fact_helper(object,:minus,&block)
end

#retrieve(c) ⇒ Object



217
218
219
# File 'lib/core/engine.rb', line 217

def retrieve(c)
  facts.select {|f| f.kind_of?(c)}
end