Class: Crimson::Client

Inherits:
Object
  • Object
show all
Defined in:
lib/crimson/client.rb

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(id, connection) ⇒ Client

Returns a new instance of Client.



10
11
12
13
14
15
16
17
# File 'lib/crimson/client.rb', line 10

def initialize(id, connection)
  @id = id

  @connection = connection
  @connection.onmessage(&method(:on_message))

  @notification_bus = NotificationBus.new
end

Instance Attribute Details

#connectionObject (readonly)

Returns the value of attribute connection.



8
9
10
# File 'lib/crimson/client.rb', line 8

def connection
  @connection
end

#idObject (readonly)

Returns the value of attribute id.



8
9
10
# File 'lib/crimson/client.rb', line 8

def id
  @id
end

#notification_busObject (readonly)

Returns the value of attribute notification_bus.



8
9
10
# File 'lib/crimson/client.rb', line 8

def notification_bus
  @notification_bus
end

Instance Method Details

#==(other) ⇒ Object



74
75
76
# File 'lib/crimson/client.rb', line 74

def ==(other)
  other.is_a?(Client) && other.id == id
end

#eql?(other) ⇒ Boolean

Returns:

  • (Boolean)


78
79
80
# File 'lib/crimson/client.rb', line 78

def eql?(other)
  self == other
end

#hashObject



82
83
84
# File 'lib/crimson/client.rb', line 82

def hash
  id.hash
end

#observe(object) ⇒ Object



44
45
46
47
48
49
50
51
52
53
54
55
56
# File 'lib/crimson/client.rb', line 44

def observe(object)
  object.postordered_each do |observable|
    write(
      action: :create,
      id: observable.id,
      tag: observable.tag,
      changes: observable.master
    )

    observable.add_observer(self)
    notification_bus.register(observable)
  end
end

#observing?(object) ⇒ Boolean

Returns:

  • (Boolean)


70
71
72
# File 'lib/crimson/client.rb', line 70

def observing?(object)
  object.observers.key?(self)
end

#on_commit(object, changes) ⇒ Object



36
37
38
39
40
41
42
# File 'lib/crimson/client.rb', line 36

def on_commit(object, changes)
  write(
    action: :update,
    id: object.id,
    changes: changes
  )
end

#on_message(message, type) ⇒ Object



19
20
21
22
23
24
25
26
27
28
29
30
# File 'lib/crimson/client.rb', line 19

def on_message(message, type)
  message = Hashie::Mash.new(JSON.parse(message))

  begin
    case message.action
    when "event"
      notification_bus.notify(message)
    end
  rescue ArgumentError => e
    puts e
  end
end

#unobserve(object) ⇒ Object



58
59
60
61
62
63
64
65
66
67
68
# File 'lib/crimson/client.rb', line 58

def unobserve(object)
  object.postordered_each do |observable|
    observable.remove_observer(self)
    notification_bus.unregister(observable)

    write(
      action: :destroy,
      id: observable.id
    )
  end
end

#write(message = {}) ⇒ Object



32
33
34
# File 'lib/crimson/client.rb', line 32

def write(message = {})
  connection.send(message.to_json)
end