Skip to content

Commit

Permalink
Made Pusher a module and moved channel code to separate file
Browse files Browse the repository at this point in the history
  • Loading branch information
mloughran committed Apr 14, 2010
1 parent 6249f2b commit 96e45b4
Show file tree
Hide file tree
Showing 2 changed files with 44 additions and 44 deletions.
50 changes: 6 additions & 44 deletions lib/pusher.rb
Expand Up @@ -4,14 +4,13 @@

autoload 'Logger', 'logger'

class Pusher

module Pusher
class ArgumentError < ::ArgumentError
def message
'You must configure both Pusher.key in order to authenticate your Pusher app'
end
end

class << self
attr_accessor :host, :port, :logger
attr_writer :logger
Expand All @@ -26,51 +25,14 @@ def logger
end
end

self.host = 'api.pusherapp.com'
self.port = 80
self.host = 'api.pusherapp.com'
self.port = 80

def self.[](channel_id)
raise ArgumentError unless @key
@channels ||= {}
@channels[channel_id.to_s] = Channel.new(@key, channel_id)
end

class Channel
def initialize(key, id)
@uri = URI.parse("http://#{Pusher.host}:#{Pusher.port}/app/#{key}/channel/#{id}")
@http = Net::HTTP.new(@uri.host, @uri.port)
end

def trigger(event_name, data, socket_id = nil)
begin
@http.post(
@uri.path,
self.class.turn_into_json({
:event => event_name,
:data => data,
:socket_id => socket_id
}),
{'Content-Type'=> 'application/json'}
)
rescue StandardError => e
handle_error e
end
end

def self.turn_into_json(data)
if Object.const_defined?('ActiveSupport')
data.to_json
else
JSON.generate(data)
end
end

private

def handle_error(e)
self.logger.error(e.backtrace.join("\n"))
end

end

end

require 'pusher/channel'
38 changes: 38 additions & 0 deletions lib/pusher/channel.rb
@@ -0,0 +1,38 @@
module Pusher
class Channel
def initialize(key, id)
@uri = URI.parse("http://#{Pusher.host}:#{Pusher.port}/app/#{key}/channel/#{id}")
@http = Net::HTTP.new(@uri.host, @uri.port)
end

def trigger(event_name, data, socket_id = nil)
begin
@http.post(
@uri.path,
self.class.turn_into_json({
:event => event_name,
:data => data,
:socket_id => socket_id
}),
{'Content-Type'=> 'application/json'}
)
rescue StandardError => e
handle_error e
end
end

def self.turn_into_json(data)
if Object.const_defined?('ActiveSupport')
data.to_json
else
JSON.generate(data)
end
end

private

def handle_error(e)
self.logger.error(e.backtrace.join("\n"))
end
end
end

0 comments on commit 96e45b4

Please sign in to comment.