Skip to content

Commit

Permalink
Try to organize some code.
Browse files Browse the repository at this point in the history
Signed-off-by: François de Metz <[email protected]>
  • Loading branch information
francois2metz committed Jul 28, 2011
1 parent 83f73e1 commit faca7d1
Show file tree
Hide file tree
Showing 3 changed files with 57 additions and 25 deletions.
18 changes: 9 additions & 9 deletions README.md
Original file line number Diff line number Diff line change
@@ -1,15 +1,15 @@
# EventSource client for EventMachine

source = EM::EventSource.new ("/live/meeting", {:start => 0})
source = EM::EventSource.new ("/live/meeting", {:start => 0})

source.message do |message|
end
source.message do |message|
end

source.error do |error|
end
source.error do |error|
end

source.on "plop" do |message|
end
source.on "plop" do |message|
end

source.start
source.close
source.start
source.close
19 changes: 19 additions & 0 deletions em-eventsource.gemspec
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
Gem::Specification.new do |s|
s.name = "em-eventsource"
s.version = "0.0.1"
s.date = Time.now.utc.strftime("%Y-%m-%d")
s.homepage = "http://github.com/af83/em-eventsource"
s.authors = "François de Metz"
s.email = "[email protected]"
s.description = ""
s.summary = ""
s.extra_rdoc_files = %w(README.md)
s.files = Dir["LICENSE", "README.md", "Gemfile", "lib/**/*.rb"]
s.require_paths = ["lib"]
s.rubygems_version = %q{1.3.7}
s.add_dependency "eventmachine", "1.0.0.beta3"
s.add_dependency "em-http-request", "1.0.0.beta4"
s.add_development_dependency "minitest", "~>2.0"
s.add_development_dependency "bundler"
s.add_development_dependency "rake"
end
45 changes: 29 additions & 16 deletions lib/em-eventsource.rb
Original file line number Diff line number Diff line change
@@ -1,31 +1,50 @@
require "eventmachine"
require "em-http-request"

module EventMachine
class EventSource
def initialize(url, query={}, headers={})
@Url = url
@url = url
@query = query
@headers = headers

@closed = false
@lastid = nil
@retry = 3 # seconds

@errors = []
@messages = []
@on = {}
end

def on(type, &block)

@on[type] << block
end

def message(&block)

@messages << block
end

def error(&block)
@errors << block
end

# Start subscription
def start
@closed = false
listen
end

# Cancel subscription
def close
@closed = true
@req.close
end

protected

def listen
@req = prepare_request(:get, @url,
{ :query => @query,
:head => {'Last-Event-Id' => @lastid }.merge(@headers)})
@req = prepare_request
@req.errback do
next if @canceled
EM.add_timer(@retry) do
Expand Down Expand Up @@ -54,16 +73,10 @@ def listen
end
end

# Start subscription
def start
@closed = false
listen
end

# Cancel subscription
def close
@closed = true
@req.close
def prepare_request
conn = EM::HttpRequest.new(@url)
conn.get({ :query => @query,
:head => {'Last-Event-Id' => @lastid }.merge(@headers)})
end
end
end

0 comments on commit faca7d1

Please sign in to comment.