Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Remove the use of Crack and Json and instead use MultiJson #2

Closed
wants to merge 6 commits into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,7 @@ coverage
rdoc
pkg
.yardoc
Gemfile.lock

## PROJECT::SPECIFIC
.bundle
43 changes: 0 additions & 43 deletions Gemfile.lock

This file was deleted.

7 changes: 3 additions & 4 deletions lib/pusher.rb
Original file line number Diff line number Diff line change
Expand Up @@ -26,12 +26,12 @@ class << self
# @private
def logger
@logger ||= begin
log = Logger.new(STDOUT)
log = Logger.new($stdout)
log.level = Logger::INFO
log
end
end

# @private
def authentication_token
Signature::Token.new(@key, @secret)
Expand Down Expand Up @@ -103,6 +103,5 @@ def self.[](channel_name)
end
end

require 'pusher/json'
require 'pusher/channel'
require 'pusher/request'
require 'pusher/request'
15 changes: 8 additions & 7 deletions lib/pusher/channel.rb
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
require 'crack/core_extensions' # Used for Hash#to_params
require 'pusher/core_ext/hash'
require 'hmac-sha2'
require 'multi_json'

module Pusher
# Trigger events on Channels
Expand Down Expand Up @@ -28,13 +29,13 @@ def trigger_async(event_name, data, socket_id = nil, &block)
raise Error, "In order to use trigger_async you must be running inside an eventmachine loop"
end
require 'em-http' unless defined?(EventMachine::HttpRequest)

@http_async ||= EventMachine::HttpRequest.new(@uri)

request = Pusher::Request.new(@uri, event_name, data, socket_id)

deferrable = EM::DefaultDeferrable.new

http = @http_async.post({
:query => request.query, :timeout => 5, :body => request.body,
:head => {'Content-Type'=> 'application/json'}
Expand All @@ -51,7 +52,7 @@ def trigger_async(event_name, data, socket_id = nil, &block)
Pusher.logger.debug("Network error connecting to pusher: #{http.inspect}")
deferrable.fail(Error.new("Network error connecting to pusher"))
}

deferrable
end

Expand Down Expand Up @@ -111,7 +112,7 @@ def trigger(event_name, data, socket_id = nil)
Pusher.logger.error("#{e.message} (#{e.class})")
Pusher.logger.debug(e.backtrace.join("\n"))
end

# Compute authentication string required to subscribe to this channel.
#
# See http://pusherapp.com/docs/auth_signatures for more details.
Expand All @@ -133,7 +134,7 @@ def authentication_string(socket_id, custom_string = nil)

return "#{token.key}:#{signature}"
end

# Deprecated - for backward compatibility
alias :socket_auth :authentication_string

Expand All @@ -159,7 +160,7 @@ def authentication_string(socket_id, custom_string = nil)
# @private Custom data is sent to server as JSON-encoded string
#
def authenticate(socket_id, custom_data = nil)
custom_data = Pusher::JSON.generate(custom_data) if custom_data
custom_data = MultiJson.encode(custom_data) if custom_data
auth = socket_auth(socket_id, custom_data)
r = {:auth => auth}
r[:channel_data] = custom_data if custom_data
Expand Down
64 changes: 64 additions & 0 deletions lib/pusher/core_ext/hash.rb
Original file line number Diff line number Diff line change
@@ -0,0 +1,64 @@
module Pusher
module HashExt#:nodoc:
# @return <String> This hash as a query string
#
# @example
# { :name => "Bob",
# :address => {
# :street => '111 Ruby Ave.',
# :city => 'Ruby Central',
# :phones => ['111-111-1111', '222-222-2222']
# }
# }.to_params
# #=> "name=Bob&address[city]=Ruby Central&address[phones][]=111-111-1111&address[phones][]=222-222-2222&address[street]=111 Ruby Ave."
def to_params
params = self.map { |k,v| normalize_param(k,v) }.join
params.chop! # trailing &
params
end

# @param key<Object> The key for the param.
# @param value<Object> The value for the param.
#
# @return <String> This key value pair as a param
#
# @example normalize_param(:name, "Bob Jones") #=> "name=Bob%20Jones&"
def normalize_param(key, value)
param = ''
stack = []

if value.is_a?(Array)
param << value.map { |element| normalize_param("#{key}[]", element) }.join
elsif value.is_a?(Hash)
stack << [key,value]
else
param << "#{key}=#{URI.encode(value.to_s, Regexp.new("[^#{URI::PATTERN::UNRESERVED}]"))}&"
end

stack.each do |parent, hash|
hash.each do |key, value|
if value.is_a?(Hash)
stack << ["#{parent}[#{key}]", value]
else
param << normalize_param("#{parent}[#{key}]", value)
end
end
end

param
end

# @return <String> The hash as attributes for an XML tag.
#
# @example
# { :one => 1, "two"=>"TWO" }.to_xml_attributes
# #=> 'one="1" two="TWO"'
def to_xml_attributes
map do |k,v|
%{#{k.to_s.snake_case.sub(/^(.{1,1})/) { |m| m.downcase }}="#{v}"}
end.join(' ')
end
end
end

Hash.send :include, Pusher::HashExt
15 changes: 0 additions & 15 deletions lib/pusher/json.rb

This file was deleted.

5 changes: 3 additions & 2 deletions lib/pusher/request.rb
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
require 'signature'
require 'digest/md5'
require 'multi_json'

module Pusher
class Request
Expand All @@ -16,8 +17,8 @@ def initialize(resource, event_name, data, socket_id, token = nil)
data
else
begin
Pusher::JSON.generate(data)
rescue => e
MultiJson.encode(data)
rescue MultiJson::DecodeError => e
Pusher.logger.error("Could not convert #{data.inspect} into JSON")
raise e
end
Expand Down
18 changes: 9 additions & 9 deletions pusher.gemspec
Original file line number Diff line number Diff line change
Expand Up @@ -10,15 +10,15 @@ Gem::Specification.new do |s|
s.homepage = "http://github.com/newbamboo/pusher-gem"
s.summary = %q{Pusherapp client}
s.description = %q{Wrapper for pusherapp.com REST api}
s.add_dependency "json", "~> 1.4.0"
s.add_dependency "crack", "~> 0.1.0"
s.add_dependency "ruby-hmac", "~> 0.4.0"
s.add_dependency 'signature', "~> 0.1.2"

s.add_development_dependency "rspec", "~> 2.0"
s.add_development_dependency "webmock"
s.add_development_dependency "em-http-request", "~> 0.2.7"

s.add_dependency 'multi_json', '~> 1.0.1'
s.add_dependency 'ruby-hmac', '~> 0.4.0'
s.add_dependency 'signature', '~> 0.1.2'

s.add_development_dependency 'rspec', '~> 2.0'
s.add_development_dependency 'webmock'
s.add_development_dependency 'em-http-request', '~> 0.2.7'
s.add_development_dependency 'yajl-ruby', '~> 0.8.2'

s.files = `git ls-files`.split("\n")
s.test_files = `git ls-files -- {test,spec,features}/*`.split("\n")
Expand Down
40 changes: 17 additions & 23 deletions spec/channel_spec.rb
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
require File.expand_path('../spec_helper', __FILE__)
require 'spec_helper'

describe Pusher::Channel do
before do
Expand All @@ -20,7 +20,7 @@
Pusher.key = nil
Pusher.secret = nil
end

describe 'trigger!' do
before :each do
WebMock.stub_request(:post, @pusher_url_regexp).
Expand Down Expand Up @@ -50,7 +50,7 @@
query_hash["auth_key"].should == Pusher.key
query_hash["auth_timestamp"].should_not be_nil

parsed = JSON.parse(req.body)
parsed = MultiJson.decode(req.body)
parsed.should == {
"name" => 'Pusher',
"last_name" => 'App'
Expand All @@ -68,12 +68,6 @@
end
end

it "should raise error on non string values with cannot be jsonified" do
lambda {
@channel.trigger!('new_event', Object.new)
}.should raise_error(JSON::GeneratorError)
end

it "should catch all Net::HTTP exceptions and raise a Pusher::HTTPError, exposing the original error if required" do
WebMock.stub_request(
:post, %r{/apps/20/channels/test_channel/events}
Expand All @@ -92,7 +86,7 @@

it "should raise AuthenticationError if pusher returns 401" do
WebMock.stub_request(
:post,
:post,
%r{/apps/20/channels/test_channel/events}
).to_return(:status => 401)
lambda {
Expand Down Expand Up @@ -211,48 +205,48 @@
}.should raise_error
end
end

describe 'with extra string argument' do

it 'should be a string or nil' do
lambda {
@channel.socket_auth('socketid', 'boom')
}.should_not raise_error

lambda {
@channel.socket_auth('socketid', 123)
}.should raise_error

lambda {
@channel.socket_auth('socketid', nil)
}.should_not raise_error

lambda {
@channel.socket_auth('socketid', {})
}.should raise_error
end

it "should return an authentication string given a socket id and custom args" do
auth = @channel.socket_auth('socketid', 'foobar')

auth.should == "12345678900000001:#{HMAC::SHA256.hexdigest(Pusher.secret, "socketid:test_channel:foobar")}"
end

end
end

describe '#authenticate' do

before :each do
@channel = Pusher['test_channel']
@custom_data = {:uid => 123, :info => {:name => 'Foo'}}
end

it 'should return a hash with signature including custom data and data as json string' do
Pusher::JSON.stub!(:generate).with(@custom_data).and_return 'a json string'
MultiJson.stub!(:encode).with(@custom_data).and_return 'a json string'

response = @channel.authenticate('socketid', @custom_data)

response.should == {
:auth => "12345678900000001:#{HMAC::SHA256.hexdigest(Pusher.secret, "socketid:test_channel:a json string")}",
:channel_data => 'a json string'
Expand Down
2 changes: 1 addition & 1 deletion spec/pusher_spec.rb
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
require File.expand_path('../spec_helper', __FILE__)
require 'spec_helper'

require 'em-http'

Expand Down
9 changes: 5 additions & 4 deletions spec/spec_helper.rb
Original file line number Diff line number Diff line change
@@ -1,13 +1,14 @@
require 'rubygems'
begin
require 'bundler/setup'
rescue LoadError
puts 'although not required, it is recommended that you use bundler when running the tests'
end

require 'rspec'
require 'rspec/autorun'
require 'em-http' # As of webmock 1.4.0, em-http must be loaded first
require 'webmock/rspec'

$LOAD_PATH.unshift(File.dirname(__FILE__))
$LOAD_PATH.unshift(File.join(File.dirname(__FILE__), '..', 'lib'))

require 'pusher'
require 'eventmachine'

Expand Down