Class: Primrose::Observable

Inherits:
Object
  • Object
show all
Defined in:
lib/primrose/observable.rb

Instance Method Summary collapse

Constructor Details

#initialize(value) ⇒ Observable

Returns a new instance of Observable.



5
6
7
8
9
10
# File 'lib/primrose/observable.rb', line 5

def initialize(value)
  @value = value
  @listeners = []
  @previous_value = deep_clone(value)
  @events = {}
end

Instance Method Details

#alter(new_value) ⇒ Object



39
40
41
42
43
# File 'lib/primrose/observable.rb', line 39

def alter(new_value)
  @previous_value = deep_clone(@value)
  @value = new_value
  notify_observers
end

#follow(&block) ⇒ Object



12
13
14
15
# File 'lib/primrose/observable.rb', line 12

def follow(&block)
  @listeners << block
  block.call(@value, @previous_value)
end

#load_state(key) ⇒ Object



32
33
34
35
36
37
# File 'lib/primrose/observable.rb', line 32

def load_state(key)
  if File.exist?("#{key}.json")
    @value = JSON.parse(File.read("#{key}.json"))
    notify_observers
  end
end

#on(event_name, &block) ⇒ Object



17
18
19
# File 'lib/primrose/observable.rb', line 17

def on(event_name, &block)
  (@events[event_name] ||= []) << block
end

#save_state(key) ⇒ Object

State Persistence



28
29
30
# File 'lib/primrose/observable.rb', line 28

def save_state(key)
  File.write("#{key}.json", @value.to_json)
end

#trigger(event_name, *args) ⇒ Object



21
22
23
24
25
# File 'lib/primrose/observable.rb', line 21

def trigger(event_name, *args)
  (@events[event_name] || []).each do |listener|
    listener.call(*args)
  end
end

#valueObject



45
46
47
# File 'lib/primrose/observable.rb', line 45

def value
  @value
end