Class: Aristotle::Logic

Inherits:
Object
  • Object
show all
Defined in:
lib/aristotle/logic.rb

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(object) ⇒ Logic

Returns a new instance of Logic.



3
4
5
# File 'lib/aristotle/logic.rb', line 3

def initialize(object)
  @object = object
end

Class Method Details

.action(expression, &block) ⇒ Object

called when class is loaded



31
32
33
34
# File 'lib/aristotle/logic.rb', line 31

def self.action(expression, &block)
  @actions ||= {}
  @actions[expression] = block
end

.commands(logic_method = nil) ⇒ Object



19
20
21
22
# File 'lib/aristotle/logic.rb', line 19

def self.commands(logic_method = nil)
  load_commands
  logic_method.nil? ? @commands : (@commands[logic_method] || [])
end

.condition(expression, &block) ⇒ Object

called when class is loaded



25
26
27
28
# File 'lib/aristotle/logic.rb', line 25

def self.condition(expression, &block)
  @conditions ||= {}
  @conditions[expression] = block
end

.html_rulesObject



59
60
61
# File 'lib/aristotle/logic.rb', line 59

def self.html_rules
  Aristotle::Presenter.new(self).html_rules
end

.load_commandsObject



36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
# File 'lib/aristotle/logic.rb', line 36

def self.load_commands
  @commands ||= {}

  return if @commands != {}

  filename = "app/logic/#{logic_name}.logic"
  logic_data = File.read(filename)

  command = nil

  lines = logic_data.split("\n").map(&:rstrip).select { |l| l != '' && !l.strip.start_with?('#') }
  lines.each do |line|
    if line.start_with? '  '
      raise "#{filename} is broken!" if command.nil?

      @commands[command] ||= []
      @commands[command] << Aristotle::Command.new(line.strip, @conditions || {}, @actions || {})
    else
      command = line
    end
  end
end

.logic_nameObject



63
64
65
# File 'lib/aristotle/logic.rb', line 63

def self.logic_name
  self.to_s.gsub(/Logic$/, '').gsub(/([a-z])([A-Z])/, '\1_\2').downcase
end

Instance Method Details

#process(logic_method, return_command: false) ⇒ Object



7
8
9
10
11
12
13
14
15
16
17
# File 'lib/aristotle/logic.rb', line 7

def process(logic_method, return_command: false)
  self.class.commands(logic_method).each do |command|
    next unless command.condition_passes_with?(@object)

    return_value = command.do_action_with(@object)

    return return_command ? command : return_value
  end

  nil
end