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 create 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.



180
181
182
183
184
185
186
# File 'lib/core/engine.rb', line 180

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



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

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.



216
217
218
219
220
221
222
# File 'lib/core/engine.rb', line 216

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

#factsObject



188
189
190
# File 'lib/core/engine.rb', line 188

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.



226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
# File 'lib/core/engine.rb', line 226

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   
      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.



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

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


244
245
246
247
# File 'lib/core/engine.rb', line 244

def print
  @working_memory.print
  @root.print
end

#retract(object, &block) ⇒ Object

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



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

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

#retrieve(c) ⇒ Object



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

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