Class: Metacosm::Simulation

Inherits:
Object
  • Object
show all
Defined in:
lib/metacosm/simulation.rb

Instance Attribute Summary collapse

Class Method Summary collapse

Instance Method Summary collapse

Instance Attribute Details

#runningObject

Returns the value of attribute running.



3
4
5
# File 'lib/metacosm/simulation.rb', line 3

def running
  @running
end

Class Method Details

.currentObject



58
59
60
# File 'lib/metacosm/simulation.rb', line 58

def self.current
  @current ||= new
end

Instance Method Details

#apply(command) ⇒ Object



37
38
39
40
41
# File 'lib/metacosm/simulation.rb', line 37

def apply(command)
  mutex.synchronize do
    handler_for(command).handle(command.attrs)
  end
end

#clear!Object



62
63
64
# File 'lib/metacosm/simulation.rb', line 62

def clear!
  @events = []
end

#command_queueObject



12
13
14
# File 'lib/metacosm/simulation.rb', line 12

def command_queue
  @command_queue ||= Queue.new
end

#conduct!Object



16
17
18
# File 'lib/metacosm/simulation.rb', line 16

def conduct!
  @conductor_thread = Thread.new { execute }
end

#construct_listener_for(event) ⇒ Object (protected)



77
78
79
80
# File 'lib/metacosm/simulation.rb', line 77

def construct_listener_for(event)
  listener = Object.const_get(event.class.name.split('::').last + "Listener").new(self)
  listener
end

#eventsObject



54
55
56
# File 'lib/metacosm/simulation.rb', line 54

def events
  @events ||= []
end

#executeObject



20
21
22
23
24
25
26
27
# File 'lib/metacosm/simulation.rb', line 20

def execute
  while true
    if (command=command_queue.pop)
      apply(command)
    end
    sleep 0.01
  end
end

#fire(command) ⇒ Object



8
9
10
# File 'lib/metacosm/simulation.rb', line 8

def fire(command)
  command_queue.push(command)
end

#halt!Object



29
30
31
# File 'lib/metacosm/simulation.rb', line 29

def halt!
  @conductor_thread.terminate
end

#handler_for(command) ⇒ Object (protected)



67
68
69
70
# File 'lib/metacosm/simulation.rb', line 67

def handler_for(command)
  @handlers ||= {}
  @handlers[command.class] ||= Object.const_get(command.class.name.split('::').last + "Handler").new
end

#listener_for(event) ⇒ Object (protected)



72
73
74
75
# File 'lib/metacosm/simulation.rb', line 72

def listener_for(event)
  @listeners ||= {}
  @listeners[event.class] ||= construct_listener_for(event)
end

#mutexObject



33
34
35
# File 'lib/metacosm/simulation.rb', line 33

def mutex
  @mutex = Mutex.new
end

#receive(event, record: true) ⇒ Object



43
44
45
46
47
48
49
50
51
52
# File 'lib/metacosm/simulation.rb', line 43

def receive(event, record: true)
  events.push(event) if record

  listener = listener_for(event)
  if event.attrs.any?
    listener.receive(event.attrs)
  else
    listener.receive
  end
end

#watch(model) ⇒ Object



4
5
6
# File 'lib/metacosm/simulation.rb', line 4

def watch(model)
  Frappuccino::Stream.new(model).on_value(&method(:receive))
end