Skip to content

Commit

Permalink
Syncer#on now accepts a proc
Browse files Browse the repository at this point in the history
  • Loading branch information
erdnaxeli committed Dec 2, 2020
1 parent f45eed1 commit bf6e173
Show file tree
Hide file tree
Showing 5 changed files with 29 additions and 8 deletions.
1 change: 0 additions & 1 deletion spec/spec_helper.cr
Original file line number Diff line number Diff line change
@@ -1,7 +1,6 @@
require "spec"
require "../src/caridina"


SYNC = %(
{
"next_batch": "s72595_4483_1934",
Expand Down
16 changes: 16 additions & 0 deletions spec/syncer_spec.cr
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,23 @@ require "../src/syncer"

require "./spec_helper"

def listener(event)
puts event
end

describe Caridina::Syncer do
it "accepts blocks" do
syncer = Caridina::Syncer.new
syncer.on(Caridina::Events::Message) do |event|
puts event
end
end

it "accepts proc" do
syncer = Caridina::Syncer.new
syncer.on(Caridina::Events::Message, ->listener(Caridina::Events::Event))
end

it "sends events to listeners without source" do
received_event = nil
calls = 0
Expand Down
2 changes: 1 addition & 1 deletion src/events/base.cr
Original file line number Diff line number Diff line change
Expand Up @@ -61,6 +61,6 @@ module Caridina::Events
class Content < Event::Content
end

getter content : Nil = nil
getter content : Content? = nil
end
end
2 changes: 1 addition & 1 deletion src/events/state_events.cr
Original file line number Diff line number Diff line change
Expand Up @@ -116,7 +116,7 @@ module Caridina::Events
# set it up ourself.
property room_id : String?

def content #: Event::Content
def content : Event::Content
json = @json_unmapped["content"].to_json

{% begin %}
Expand Down
16 changes: 11 additions & 5 deletions src/syncer.cr
Original file line number Diff line number Diff line change
Expand Up @@ -49,12 +49,18 @@ class Caridina::Syncer
end
end

def on(event_type : Events::Event.class, source = Source::All, &block : EventListener) : Nil
if !@listeners.has_key?(event_type)
@listeners[event_type] = Array(Tuple(EventListener, Source)).new
end
def on(event_type : Events::Event.class, source = Source::All, &listener : EventListener) : Nil
on(event_type, source, listener)
end

@listeners[event_type] << {block, source}
def on(event_type : Events::Event.class, source = Source::All, listener : EventListener? = nil) : Nil
if !listener.nil?
if !@listeners.has_key?(event_type)
@listeners[event_type] = Array(Tuple(EventListener, Source)).new
end

@listeners[event_type] << {listener, source}
end
end

private def dispatch(event, event_source) : Nil
Expand Down

0 comments on commit bf6e173

Please sign in to comment.