Skip to content

HTTPS clone URL

Subversion checkout URL

You can clone with HTTPS or Subversion.

Download ZIP
Browse files

Merge pull request #391 from nysthee/fix/ruby-style-mitigations

 Fix/ruby style mitigations
  • Loading branch information...
commit 166e8822a977e626346c9510b6126ba4f5fa6afc 2 parents 3b12131 + aec1e8e
@jnunemaker authored
Showing with 421 additions and 230 deletions.
  1. +92 −0 .rubocop.yml
  2. +124 −0 .rubocop_todo.yml
  3. +1 −1  Guardfile
  4. +7 −8 bin/httparty
  5. +2 −2 examples/aaws.rb
  6. +1 −1  examples/crack.rb
  7. +1 −4 examples/custom_parsers.rb
  8. +3 −3 examples/delicious.rb
  9. +2 −2 examples/google.rb
  10. +5 −7 examples/logging.rb
  11. +0 −1  examples/nokogiri_html_parser.rb
  12. +3 −3 examples/rubyurl.rb
  13. +2 −2 examples/twitter.rb
  14. +1 −1  examples/whoismyrep.rb
  15. +1 −1  features/steps/env.rb
  16. +2 −2 features/steps/mongrel_helper.rb
  17. +3 −3 features/steps/remote_service_steps.rb
  18. +4 −4 httparty.gemspec
  19. +36 −40 lib/httparty.rb
  20. +3 −4 lib/httparty/connection_adapter.rb
  21. +2 −3 lib/httparty/cookie_hash.rb
  22. +2 −2 lib/httparty/hash_conversions.rb
  23. +1 −1  lib/httparty/logger/apache_logger.rb
  24. +1 −1  lib/httparty/logger/logger.rb
  25. +1 −1  lib/httparty/module_inheritable_attributes.rb
  26. +14 −14 lib/httparty/net_digest_auth.rb
  27. +11 −14 lib/httparty/request.rb
  28. +3 −3 lib/httparty/response.rb
  29. +0 −2  spec/httparty/connection_adapter_spec.rb
  30. +5 −5 spec/httparty/cookie_hash_spec.rb
  31. +1 −1  spec/httparty/exception_spec.rb
  32. +3 −3 spec/httparty/logger/logger_spec.rb
  33. +26 −26 spec/httparty/net_digest_auth_spec.rb
  34. +3 −1 spec/httparty/parser_spec.rb
  35. +18 −24 spec/httparty/request_spec.rb
  36. +10 −10 spec/httparty_spec.rb
  37. +3 −6 spec/spec_helper.rb
  38. +2 −2 spec/support/ssl_test_helper.rb
  39. +21 −21 spec/support/ssl_test_server.rb
  40. +1 −1  spec/support/stub_response.rb
View
92 .rubocop.yml
@@ -0,0 +1,92 @@
+inherit_from: .rubocop_todo.yml
+
+# Offense count: 963
+# Cop supports --auto-correct.
+# Configuration parameters: EnforcedStyle, SupportedStyles.
+Style/StringLiterals:
+ Enabled: false
+
+# Offense count: 327
+# Cop supports --auto-correct.
+# Configuration parameters: EnforcedStyle, EnforcedStyleForEmptyBraces, SupportedStyles.
+Style/SpaceInsideHashLiteralBraces:
+ Enabled: false
+
+# Offense count: 33
+# Cop supports --auto-correct.
+# Configuration parameters: EnforcedStyle, SupportedStyles, EnforcedStyleForEmptyBraces, SpaceBeforeBlockParameters.
+Style/SpaceInsideBlockBraces:
+ Enabled: false
+
+# Offense count: 1
+# Cop supports --auto-correct.
+Style/SpaceBeforeSemicolon:
+ Enabled: false
+
+# Offense count: 20
+# Cop supports --auto-correct.
+# Configuration parameters: EnforcedStyle, SupportedStyles.
+Style/SignalException:
+ Enabled: false
+
+# Offense count: 1
+# Configuration parameters: Methods.
+Style/SingleLineBlockParams:
+ Enabled: false
+
+# Offense count: 6
+# Cop supports --auto-correct.
+Style/PerlBackrefs:
+ Enabled: false
+
+# Offense count: 2
+# Cop supports --auto-correct.
+# Configuration parameters: AllowAsExpressionSeparator.
+Style/Semicolon:
+ Enabled: false
+
+# Offense count: 77
+# Cop supports --auto-correct.
+# Configuration parameters: EnforcedStyle, SupportedStyles.
+Style/BracesAroundHashParameters:
+ Enabled: false
+
+# Offense count: 36
+Style/Documentation:
+ Enabled: false
+
+# Offense count: 6
+# Cop supports --auto-correct.
+# Configuration parameters: EnforcedStyle, SupportedStyles, AllowInnerSlashes.
+Style/RegexpLiteral:
+ Enabled: false
+
+# Offense count: 5
+# Cop supports --auto-correct.
+Style/NumericLiterals:
+ MinDigits: 6
+
+# Offense count: 4
+# Cop supports --auto-correct.
+Lint/UnusedMethodArgument:
+ Enabled: false
+
+# Offense count: 11
+# Cop supports --auto-correct.
+Lint/UnusedBlockArgument:
+ Enabled: false
+
+# Offense count: 1
+Lint/Void:
+ Enabled: false
+
+# Offense count: 22
+# Cop supports --auto-correct.
+# Configuration parameters: EnforcedStyle, SupportedStyles.
+Style/IndentHash:
+ Enabled: false
+
+# Offense count: 7
+# Configuration parameters: MinBodyLength.
+Style/GuardClause:
+ Enabled: false
View
124 .rubocop_todo.yml
@@ -0,0 +1,124 @@
+# This configuration was generated by `rubocop --auto-gen-config`
+# on 2015-04-24 07:22:28 +0200 using RuboCop version 0.30.0.
+# The point is for the user to remove these configuration records
+# one by one as the offenses are removed from the code base.
+# Note that changes in the inspected code, or installation of new
+# versions of RuboCop, may require this file to be generated again.
+
+# Offense count: 33
+Lint/AmbiguousRegexpLiteral:
+ Enabled: false
+
+# Offense count: 1
+# Configuration parameters: AlignWith, SupportedStyles.
+Lint/EndAlignment:
+ Enabled: false
+
+# Offense count: 1
+Lint/HandleExceptions:
+ Enabled: false
+
+# Offense count: 5
+Lint/UselessAssignment:
+ Enabled: false
+
+# Offense count: 23
+Metrics/AbcSize:
+ Max: 86
+
+# Offense count: 1
+# Configuration parameters: CountComments.
+Metrics/ClassLength:
+ Max: 285
+
+# Offense count: 8
+Metrics/CyclomaticComplexity:
+ Max: 17
+
+# Offense count: 332
+# Configuration parameters: AllowURI, URISchemes.
+Metrics/LineLength:
+ Max: 266
+
+# Offense count: 17
+# Configuration parameters: CountComments.
+Metrics/MethodLength:
+ Max: 39
+
+# Offense count: 8
+Metrics/PerceivedComplexity:
+ Max: 20
+
+# Offense count: 1
+Style/AccessorMethodName:
+ Enabled: false
+
+# Offense count: 1
+Style/AsciiComments:
+ Enabled: false
+
+# Offense count: 14
+# Cop supports --auto-correct.
+# Configuration parameters: EnforcedStyle, SupportedStyles, ProceduralMethods, FunctionalMethods, IgnoredMethods.
+Style/BlockDelimiters:
+ Enabled: false
+
+# Offense count: 2
+Style/CaseEquality:
+ Enabled: false
+
+# Offense count: 3
+# Configuration parameters: IndentWhenRelativeTo, SupportedStyles, IndentOneStep.
+Style/CaseIndentation:
+ Enabled: false
+
+# Offense count: 4
+# Configuration parameters: EnforcedStyle, SupportedStyles.
+Style/ClassAndModuleChildren:
+ Enabled: false
+
+# Offense count: 7
+Style/ConstantName:
+ Enabled: false
+
+# Offense count: 2
+Style/EachWithObject:
+ Enabled: false
+
+# Offense count: 2
+# Cop supports --auto-correct.
+Style/ElseAlignment:
+ Enabled: false
+
+# Offense count: 3
+# Cop supports --auto-correct.
+# Configuration parameters: EnforcedStyle, SupportedStyles.
+Style/FirstParameterIndentation:
+ Enabled: false
+
+# Offense count: 2
+# Cop supports --auto-correct.
+# Configuration parameters: EnforcedStyle, SupportedStyles, UseHashRocketsWithSymbolValues.
+Style/HashSyntax:
+ Enabled: false
+
+# Offense count: 7
+# Cop supports --auto-correct.
+# Configuration parameters: MaxLineLength.
+Style/IfUnlessModifier:
+ Enabled: false
+
+# Offense count: 11
+# Cop supports --auto-correct.
+Style/Lambda:
+ Enabled: false
+
+# Offense count: 1
+# Configuration parameters: EnforcedStyle, MinBodyLength, SupportedStyles.
+Style/Next:
+ Enabled: false
+
+# Offense count: 2
+# Configuration parameters: EnforcedStyle, SupportedStyles.
+Style/RaiseArgs:
+ Enabled: false
View
2  Guardfile
@@ -1,7 +1,7 @@
rspec_options = {
version: 1,
all_after_pass: false,
- all_on_start: false,
+ all_on_start: false
}
guard 'rspec', rspec_options do
View
15 bin/httparty
@@ -3,7 +3,7 @@
require "optparse"
require "pp"
-$:.unshift(File.join(File.dirname(__FILE__), "/../lib"))
+$LOAD_PATH.unshift(File.join(File.dirname(__FILE__), "/../lib"))
require "httparty"
opts = {
@@ -13,11 +13,11 @@ opts = {
}
OptionParser.new do |o|
- o.banner = "USAGE: #{$0} [options] [url]"
+ o.banner = "USAGE: #{$PROGRAM_NAME} [options] [url]"
o.on("-f",
"--format [FORMAT]",
- "Output format to use instead of pretty-print ruby: " +
+ "Output format to use instead of pretty-print ruby: " \
"plain, csv, json or xml") do |f|
opts[:output_format] = f.downcase.to_sym
end
@@ -64,16 +64,15 @@ OptionParser.new do |o|
end
end.parse!
-
if ARGV.empty?
STDERR.puts "You need to provide a URL"
- STDERR.puts "USAGE: #{$0} [options] [url]"
+ STDERR.puts "USAGE: #{$PROGRAM_NAME} [options] [url]"
end
def dump_headers(response)
resp_type = Net::HTTPResponse::CODE_TO_OBJ[response.code.to_s]
puts "#{response.code} #{resp_type.to_s.sub(/^Net::HTTP/, '')}"
- response.headers.each do |n,v|
+ response.headers.each do |n, v|
puts "#{n}: #{v}"
end
puts
@@ -81,7 +80,7 @@ end
if opts[:verbose]
puts "#{opts[:action].to_s.upcase} #{ARGV.first}"
- opts[:headers].each do |n,v|
+ opts[:headers].each do |n, v|
puts "#{n}: #{v}"
end
puts
@@ -109,7 +108,7 @@ else
puts
when :csv
require 'csv'
- puts CSV.parse(response.body).map{|row| row.to_s }
+ puts CSV.parse(response.body).map(&:to_s)
else
puts response
end
View
4 examples/aaws.rb
@@ -4,7 +4,7 @@
dir = File.expand_path(File.join(File.dirname(__FILE__), '..', 'lib'))
require File.join(dir, 'httparty')
require 'pp'
-config = YAML::load(File.read(File.join(ENV['HOME'], '.aaws')))
+config = YAML.load(File.read(File.join(ENV['HOME'], '.aaws')))
module AAWS
class Book
@@ -16,7 +16,7 @@ def initialize(key)
self.class.default_params AWSAccessKeyId: key
end
- def search(options={})
+ def search(options = {})
raise ArgumentError, 'You must search for something' if options[:query].blank?
# amazon uses nasty camelized query params
View
2  examples/crack.rb
@@ -9,7 +9,7 @@ class Rep
include HTTParty
parser(
- Proc.new do |body, format|
+ proc do |body, format|
Crack::XML.parse(body)
end
)
View
5 examples/custom_parsers.rb
@@ -16,7 +16,6 @@ def atom
parser Parser::Atom
end
-
class OnlyParseAtom
include HTTParty
@@ -35,7 +34,6 @@ def atom
parser Parser::OnlyAtom
end
-
class SkipParsing
include HTTParty
@@ -49,11 +47,10 @@ def parse
parser Parser::Simple
end
-
class AdHocParsing
include HTTParty
parser(
- Proc.new do |body, format|
+ proc do |body, format|
case format
when :json
body.to_json
View
6 examples/delicious.rb
@@ -1,7 +1,7 @@
dir = File.expand_path(File.join(File.dirname(__FILE__), '..', 'lib'))
require File.join(dir, 'httparty')
require 'pp'
-config = YAML::load(File.read(File.join(ENV['HOME'], '.delicious')))
+config = YAML.load(File.read(File.join(ENV['HOME'], '.delicious')))
class Delicious
include HTTParty
@@ -16,7 +16,7 @@ def initialize(u, p)
# dt (optional). Filter by this date (CCYY-MM-DDThh:mm:ssZ).
# url (optional). Filter by this url.
# ie: posts(query: {tag: 'ruby'})
- def posts(options={})
+ def posts(options = {})
options.merge!({basic_auth: @auth})
self.class.get('/posts/get', options)
end
@@ -24,7 +24,7 @@ def posts(options={})
# query params that filter the posts are:
# tag (optional). Filter by this tag.
# count (optional). Number of items to retrieve (Default:15, Maximum:100).
- def recent(options={})
+ def recent(options = {})
options.merge!({basic_auth: @auth})
self.class.get('/posts/recent', options)
end
View
4 examples/google.rb
@@ -10,7 +10,7 @@ class Google
# google.com redirects to www.google.com so this is live test for redirection
pp Google.get('http://google.com')
-puts '', '*'*70, ''
+puts '', '*' * 70, ''
# check that ssl is requesting right
-pp Google.get('https://www.google.com')
View
12 examples/logging.rb
@@ -8,31 +8,29 @@
my_logger.info "Logging can be used on the main HTTParty class. It logs redirects too."
HTTParty.get "http://google.com", logger: my_logger
-my_logger.info '*'*70
+my_logger.info '*' * 70
my_logger.info "It can be used also on a custom class."
class Google
include HTTParty
- logger ::Logger.new "httparty.log"
+ logger ::Logger.new "httparty.log"
end
Google.get "http://google.com"
-my_logger.info '*'*70
+my_logger.info '*' * 70
my_logger.info "The default formatter is :apache. The :curl formatter can also be used."
my_logger.info "You can tell wich method to call on the logger too. It is info by default."
HTTParty.get "http://google.com", logger: my_logger, log_level: :debug, log_format: :curl
-
-my_logger.info '*'*70
+my_logger.info '*' * 70
my_logger.info "These configs are also available on custom classes."
class Google
include HTTParty
- logger ::Logger.new("httparty.log"), :debug, :curl
+ logger ::Logger.new("httparty.log"), :debug, :curl
end
Google.get "http://google.com"
-
View
1  examples/nokogiri_html_parser.rb
@@ -1,7 +1,6 @@
require 'rubygems'
require 'nokogiri'
-
dir = File.expand_path(File.join(File.dirname(__FILE__), '..', 'lib'))
require File.join(dir, 'httparty')
require 'pp'
View
6 examples/rubyurl.rb
@@ -6,9 +6,9 @@ class Rubyurl
include HTTParty
base_uri 'rubyurl.com'
- def self.shorten( website_url )
- post( '/api/links.json', query: { link: { website_url: website_url } } )
+ def self.shorten(website_url)
+ post('/api/links.json', query: { link: { website_url: website_url } })
end
end
-pp Rubyurl.shorten( 'http://istwitterdown.com/')
View
4 examples/twitter.rb
@@ -1,7 +1,7 @@
dir = File.expand_path(File.join(File.dirname(__FILE__), '..', 'lib'))
require File.join(dir, 'httparty')
require 'pp'
-config = YAML::load(File.read(File.join(ENV['HOME'], '.twitter')))
+config = YAML.load(File.read(File.join(ENV['HOME'], '.twitter')))
class Twitter
include HTTParty
@@ -13,7 +13,7 @@ def initialize(u, p)
# which can be :friends, :user or :public
# options[:query] can be things like since, since_id, count, etc.
- def timeline(which=:friends, options={})
+ def timeline(which = :friends, options = {})
options.merge!({basic_auth: @auth})
self.class.get("/statuses/#{which}_timeline.json", options)
end
View
2  examples/whoismyrep.rb
@@ -7,4 +7,4 @@ class Rep
end
pp Rep.get('http://whoismyrepresentative.com/getall_mems.php?zip=46544')
-pp Rep.get('http://whoismyrepresentative.com/getall_mems.php', query: {zip: 46544})
+pp Rep.get('http://whoismyrepresentative.com/getall_mems.php', query: {zip: 46544})
View
2  features/steps/env.rb
@@ -24,4 +24,4 @@ def new_port
After do
@server.stop if @server
-end
+end
View
4 features/steps/mongrel_helper.rb
@@ -10,14 +10,14 @@ def initialize
end
def process(request, response)
- instance_eval &preprocessor if preprocessor
+ instance_eval(&preprocessor) if preprocessor
reply_with(response, response_code, response_body)
end
def reply_with(response, code, response_body)
response.start(code) do |head, body|
head["Content-Type"] = content_type
- custom_headers.each { |k,v| head[k] = v }
+ custom_headers.each { |k, v| head[k] = v }
body.write(response_body)
end
end
View
6 features/steps/remote_service_steps.rb
@@ -19,7 +19,7 @@
Given /^that service takes (\d+) seconds to generate a response$/ do |time|
@server_response_time = time.to_i
- @handler.preprocessor = Proc.new { sleep time.to_i }
+ @handler.preprocessor = proc { sleep time.to_i }
end
Given /^a remote deflate service$/ do
@@ -66,12 +66,12 @@
end
Given /a restricted page at '(.*)'/ do |url|
- steps %Q{
+ steps "
Given a remote service that returns 'A response I will never see'
And that service is accessed at the path '#{url}'
And that service is protected by Basic Authentication
And that service requires the username 'something' with the password 'secret'
- }
+ "
end
# This joins the server thread, and halts cucumber, so you can actually hit the
View
8 httparty.gemspec
@@ -1,5 +1,5 @@
# -*- encoding: utf-8 -*-
-$:.push File.expand_path("../lib", __FILE__)
+$LOAD_PATH.push File.expand_path("../lib", __FILE__)
require "httparty/version"
Gem::Specification.new do |s|
@@ -10,8 +10,8 @@ Gem::Specification.new do |s|
s.authors = ["John Nunemaker", "Sandro Turriate"]
s.email = ["nunemaker@gmail.com"]
s.homepage = "http://jnunemaker.github.com/httparty"
- s.summary = %q{Makes http fun! Also, makes consuming restful web services dead easy.}
- s.description = %q{Makes http fun! Also, makes consuming restful web services dead easy.}
+ s.summary = 'Makes http fun! Also, makes consuming restful web services dead easy.'
+ s.description = 'Makes http fun! Also, makes consuming restful web services dead easy.'
s.required_ruby_version = '>= 1.9.3'
@@ -23,6 +23,6 @@ Gem::Specification.new do |s|
s.files = `git ls-files`.split("\n")
s.test_files = `git ls-files -- {test,spec,features}/*`.split("\n")
- s.executables = `git ls-files -- bin/*`.split("\n").map{ |f| File.basename(f) }
+ s.executables = `git ls-files -- bin/*`.split("\n").map { |f| File.basename(f) }
s.require_paths = ["lib"]
end
View
76 lib/httparty.rb
@@ -16,7 +16,6 @@
# @see HTTParty::ClassMethods
module HTTParty
-
def self.included(base)
base.extend ClassMethods
base.send :include, ModuleInheritableAttributes
@@ -57,14 +56,13 @@ def self.included(base)
# * :+ssl_ca_path+: see HTTParty::ClassMethods.ssl_ca_path.
module ClassMethods
-
# Turns on logging
#
# class Foo
# include HTTParty
# logger Logger.new('http_logger'), :info, :apache
# end
- def logger(logger, level=:info, format=:apache)
+ def logger(logger, level = :info, format = :apache)
default_options[:logger] = logger
default_options[:log_level] = level
default_options[:log_format] = format
@@ -76,7 +74,7 @@ def logger(logger, level=:info, format=:apache)
# include HTTParty
# http_proxy 'http://foo.com', 80, 'user', 'pass'
# end
- def http_proxy(addr=nil, port=nil, user=nil, pass=nil)
+ def http_proxy(addr = nil, port = nil, user = nil, pass = nil)
default_options[:http_proxyaddr] = addr
default_options[:http_proxyport] = port
default_options[:http_proxyuser] = user
@@ -90,7 +88,7 @@ def http_proxy(addr=nil, port=nil, user=nil, pass=nil)
# include HTTParty
# base_uri 'twitter.com'
# end
- def base_uri(uri=nil)
+ def base_uri(uri = nil)
return default_options[:base_uri] unless uri
default_options[:base_uri] = HTTParty.normalize_base_uri(uri)
end
@@ -144,7 +142,7 @@ def disable_rails_query_string_format
# include HTTParty
# default_params api_key: 'secret', another: 'foo'
# end
- def default_params(h={})
+ def default_params(h = {})
raise ArgumentError, 'Default params must an object which respond to #to_hash' unless h.respond_to?(:to_hash)
default_options[:default_params] ||= {}
default_options[:default_params].merge!(h)
@@ -201,13 +199,13 @@ def debug_output(stream = $stderr)
# include HTTParty
# headers 'Accept' => 'text/html'
# end
- def headers(h={})
+ def headers(h = {})
raise ArgumentError, 'Headers must an object which responds to #to_hash' unless h.respond_to?(:to_hash)
default_options[:headers] ||= {}
default_options[:headers].merge!(h.to_hash)
end
- def cookies(h={})
+ def cookies(h = {})
raise ArgumentError, 'Cookies must an object which respond to #to_hash' unless h.respond_to?(:to_hash)
default_cookies.add_cookies(h)
end
@@ -304,7 +302,7 @@ def resend_on_redirect(value = true)
# include HTTParty
# pem File.read('/home/user/my.pem'), "optional password"
# end
- def pem(pem_contents, password=nil)
+ def pem(pem_contents, password = nil)
default_options[:pem] = pem_contents
default_options[:pem_password] = password
end
@@ -457,7 +455,7 @@ def connection_adapter(custom_adapter = nil, options = nil)
# # Simple get with full url and query parameters
# # ie: http://foo.com/resource.json?limit=10
# Foo.get('http://foo.com/resource.json', query: {limit: 10})
- def get(path, options={}, &block)
+ def get(path, options = {}, &block)
perform_request Net::HTTP::Get, path, options, &block
end
@@ -473,75 +471,73 @@ def get(path, options={}, &block)
# # Simple post with full url using :query option,
# # which gets set as form data on the request.
# Foo.post('http://foo.com/resources', query: {bar: 'baz'})
- def post(path, options={}, &block)
+ def post(path, options = {}, &block)
perform_request Net::HTTP::Post, path, options, &block
end
# Perform a PATCH request to a path
- def patch(path, options={}, &block)
+ def patch(path, options = {}, &block)
perform_request Net::HTTP::Patch, path, options, &block
end
# Perform a PUT request to a path
- def put(path, options={}, &block)
+ def put(path, options = {}, &block)
perform_request Net::HTTP::Put, path, options, &block
end
# Perform a DELETE request to a path
- def delete(path, options={}, &block)
+ def delete(path, options = {}, &block)
perform_request Net::HTTP::Delete, path, options, &block
end
# Perform a MOVE request to a path
- def move(path, options={}, &block)
+ def move(path, options = {}, &block)
perform_request Net::HTTP::Move, path, options, &block
end
# Perform a COPY request to a path
- def copy(path, options={}, &block)
+ def copy(path, options = {}, &block)
perform_request Net::HTTP::Copy, path, options, &block
end
# Perform a HEAD request to a path
- def head(path, options={}, &block)
+ def head(path, options = {}, &block)
perform_request Net::HTTP::Head, path, options, &block
end
# Perform an OPTIONS request to a path
- def options(path, options={}, &block)
+ def options(path, options = {}, &block)
perform_request Net::HTTP::Options, path, options, &block
end
- def default_options #:nodoc:
- @default_options
- end
+ attr_reader :default_options
private
- def perform_request(http_method, path, options, &block) #:nodoc:
- options = ModuleInheritableAttributes.hash_deep_dup(default_options).merge(options)
- process_headers(options)
- process_cookies(options)
- Request.new(http_method, path, options).perform(&block)
- end
+ def perform_request(http_method, path, options, &block) #:nodoc:
+ options = ModuleInheritableAttributes.hash_deep_dup(default_options).merge(options)
+ process_headers(options)
+ process_cookies(options)
+ Request.new(http_method, path, options).perform(&block)
+ end
- def process_headers(options)
- if options[:headers] && headers.any?
- options[:headers] = headers.merge(options[:headers])
- end
+ def process_headers(options)
+ if options[:headers] && headers.any?
+ options[:headers] = headers.merge(options[:headers])
end
+ end
- def process_cookies(options) #:nodoc:
- return unless options[:cookies] || default_cookies.any?
- options[:headers] ||= headers.dup
- options[:headers]["cookie"] = cookies.merge(options.delete(:cookies) || {}).to_cookie_string
- end
+ def process_cookies(options) #:nodoc:
+ return unless options[:cookies] || default_cookies.any?
+ options[:headers] ||= headers.dup
+ options[:headers]["cookie"] = cookies.merge(options.delete(:cookies) || {}).to_cookie_string
+ end
- def validate_format
- if format && parser.respond_to?(:supports_format?) && !parser.supports_format?(format)
- raise UnsupportedFormat, "'#{format.inspect}' Must be one of: #{parser.supported_formats.map{|f| f.to_s}.sort.join(', ')}"
- end
+ def validate_format
+ if format && parser.respond_to?(:supports_format?) && !parser.supports_format?(format)
+ raise UnsupportedFormat, "'#{format.inspect}' Must be one of: #{parser.supported_formats.map(&:to_s).sort.join(', ')}"
end
+ end
end
def self.normalize_base_uri(url) #:nodoc:
View
7 lib/httparty/connection_adapter.rb
@@ -50,7 +50,6 @@ module HTTParty
# * :+ssl_ca_path+: see HTTParty::ClassMethods.ssl_ca_path.
# * :+connection_adapter_options+: contains the hash you passed to HTTParty.connection_adapter when you configured your connection adapter
class ConnectionAdapter
-
# Private: Regex used to strip brackets from IPv6 URIs.
StripIpv6BracketsRegex = /\A\[(.*)\]\z/
@@ -61,8 +60,8 @@ def self.call(uri, options)
attr_reader :uri, :options
- def initialize(uri, options={})
- raise ArgumentError, "uri must be a URI, not a #{uri.class}" unless uri.kind_of? URI
+ def initialize(uri, options = {})
+ raise ArgumentError, "uri must be a URI, not a #{uri.class}" unless uri.is_a? URI
@uri = uri
@options = options
@@ -120,7 +119,7 @@ def connection
end
end
- return http
+ http
end
private
View
5 lib/httparty/cookie_hash.rb
@@ -1,6 +1,5 @@
class HTTParty::CookieHash < Hash #:nodoc:
-
- CLIENT_COOKIES = %w{path expires domain path secure httponly}
+ CLIENT_COOKIES = %w(path expires domain path secure httponly)
def add_cookies(value)
case value
@@ -8,7 +7,7 @@ def add_cookies(value)
merge!(value)
when String
value.split('; ').each do |cookie|
- array = cookie.split('=',2)
+ array = cookie.split('=', 2)
self[array[0].to_sym] = array[1]
end
else
View
4 lib/httparty/hash_conversions.rb
@@ -12,7 +12,7 @@ module HashConversions
# }.to_params
# #=> "name=Bob&address[city]=Ruby Central&address[phones][]=111-111-1111&address[phones][]=222-222-2222&address[street]=111 Ruby Ave."
def self.to_params(hash)
- hash.to_hash.map { |k,v| normalize_param(k,v) }.join.chop
+ hash.to_hash.map { |k, v| normalize_param(k, v) }.join.chop
end
# @param key<Object> The key for the param.
@@ -28,7 +28,7 @@ def self.normalize_param(key, value)
if value.respond_to?(:to_ary)
param << value.to_ary.map { |element| normalize_param("#{key}[]", element) }.join
elsif value.respond_to?(:to_hash)
- stack << [key,value.to_hash]
+ stack << [key, value.to_hash]
else
param << "#{key}=#{ERB::Util.url_encode(value.to_s)}&"
end
View
2  lib/httparty/logger/apache_logger.rb
@@ -15,7 +15,7 @@ def format(request, response)
http_method = request.http_method.name.split("::").last.upcase
path = request.path.to_s
content_length = response.respond_to?(:headers) ? response.headers['Content-Length'] : response['Content-Length']
- @logger.send @level, "[#{TAG_NAME}] [#{current_time}] #{response.code} \"#{http_method} #{path}\" #{content_length || "-"} "
+ @logger.send @level, "[#{TAG_NAME}] [#{current_time}] #{response.code} \"#{http_method} #{path}\" #{content_length || '-'} "
end
end
end
View
2  lib/httparty/logger/logger.rb
@@ -4,7 +4,7 @@
module HTTParty
module Logger
def self.build(logger, level, formatter)
- level ||= :info
+ level ||= :info
formatter ||= :apache
case formatter
View
2  lib/httparty/module_inheritable_attributes.rb
@@ -10,7 +10,7 @@ def self.hash_deep_dup(hash)
duplicate.each_pair do |key, value|
duplicate[key] = if value.is_a?(Hash)
- hash_deep_dup(value)
+ hash_deep_dup(value)
elsif value.is_a?(Proc)
duplicate[key] = value.dup
else
View
28 lib/httparty/net_digest_auth.rb
@@ -34,23 +34,23 @@ def initialize(username, password, method, path, response_header)
def authorization_header
@cnonce = md5(random)
header = [
- %Q(Digest username="#{@username}"),
- %Q(realm="#{@response['realm']}"),
- %Q(nonce="#{@response['nonce']}"),
- %Q(uri="#{@path}"),
- %Q(response="#{request_digest}"),
+ %(Digest username="#{@username}"),
+ %(realm="#{@response['realm']}"),
+ %(nonce="#{@response['nonce']}"),
+ %(uri="#{@path}"),
+ %(response="#{request_digest}")
]
if qop_present?
fields = [
- %Q(cnonce="#{@cnonce}"),
- %Q(qop="#{@response['qop']}"),
- %Q(nc=00000001)
+ %(cnonce="#{@cnonce}"),
+ %(qop="#{@response['qop']}"),
+ "nc=00000001"
]
fields.each { |field| header << field }
end
- header << %Q(opaque="#{@response['opaque']}") if opaque_present?
+ header << %(opaque="#{@response['opaque']}") if opaque_present?
header
end
@@ -58,11 +58,11 @@ def cookie_header
@cookies
end
- private
+ private
def parse(response_header)
header = response_header['www-authenticate']
- .gsub(/qop=(auth(?:-int)?)/, %Q(qop="\\1"))
+ .gsub(/qop=(auth(?:-int)?)/, 'qop="\\1"')
header =~ /Digest (.*)/
params = {}
@@ -84,15 +84,15 @@ def parse_cookies(response_header)
end
def opaque_present?
- @response.has_key?('opaque') and not @response['opaque'].empty?
+ @response.key?('opaque') && !@response['opaque'].empty?
end
def qop_present?
- @response.has_key?('qop') and not @response['qop'].empty?
+ @response.key?('qop') && !@response['qop'].empty?
end
def random
- "%x" % (Time.now.to_i + rand(65535))
+ format "%x", (Time.now.to_i + rand(65535))
end
def request_digest
View
25 lib/httparty/request.rb
@@ -14,7 +14,7 @@ class Request #:nodoc:
SupportedURISchemes = [URI::HTTP, URI::HTTPS, URI::Generic]
- NON_RAILS_QUERY_STRING_NORMALIZER = Proc.new do |query|
+ NON_RAILS_QUERY_STRING_NORMALIZER = proc do |query|
Array(query).sort_by { |a| a[0].to_s }.map do |key, value|
if value.nil?
key.to_s
@@ -29,7 +29,7 @@ class Request #:nodoc:
attr_accessor :http_method, :options, :last_response, :redirect, :last_uri
attr_reader :path
- def initialize(http_method, path, o={})
+ def initialize(http_method, path, o = {})
self.http_method = http_method
self.path = path
self.options = {
@@ -167,7 +167,7 @@ def setup_digest_auth
auth_request.initialize_http_header(options[:headers].to_hash) if options[:headers].respond_to?(:to_hash)
res = http.request(auth_request)
- if res['www-authenticate'] != nil && res['www-authenticate'].length > 0
+ if !res['www-authenticate'].nil? && res['www-authenticate'].length > 0
@raw_request.digest_auth(username, password, res)
end
end
@@ -205,12 +205,10 @@ def get_charset
end
def encode_with_ruby_encoding(body, charset)
- begin
- encoding = Encoding.find(charset)
- body.force_encoding(encoding)
- rescue
- body
- end
+ encoding = Encoding.find(charset)
+ body.force_encoding(encoding)
+ rescue
+ body
end
def assume_utf16_is_big_endian
@@ -231,7 +229,6 @@ def encode_utf_16(body)
else
body.force_encoding("UTF-16LE")
end
-
end
def _encode_body(body)
@@ -266,7 +263,7 @@ def handle_response(body, &block)
self.path = last_response['location']
self.redirect = true
if last_response.class == Net::HTTPSeeOther
- unless options[:maintain_method_across_redirects] and options[:resend_on_redirect]
+ unless options[:maintain_method_across_redirects] && options[:resend_on_redirect]
self.http_method = Net::HTTP::Get
end
else
@@ -277,7 +274,7 @@ def handle_response(body, &block)
capture_cookies(last_response)
perform(&block)
else
- body = body || last_response.body
+ body ||= last_response.body
body = encode_body(body)
Response.new(self, last_response, lambda { parse_response(body) }, body: body)
end
@@ -314,7 +311,7 @@ def parse_response(body)
def capture_cookies(response)
return unless response['Set-Cookie']
- cookies_hash = HTTParty::CookieHash.new()
+ cookies_hash = HTTParty::CookieHash.new
cookies_hash.add_cookies(options[:headers].to_hash['Cookie']) if options[:headers] && options[:headers].to_hash['Cookie']
response.get_fields('Set-Cookie').each { |cookie| cookies_hash.add_cookies(cookie) }
options[:headers] ||= {}
@@ -347,7 +344,7 @@ def post?
def set_basic_auth_from_uri
if path.userinfo
username, password = path.userinfo.split(':')
- options[:basic_auth] = {:username => username, :password => password}
+ options[:basic_auth] = {username: username, password: password}
end
end
end
View
6 lib/httparty/response.rb
@@ -1,12 +1,12 @@
module HTTParty
class Response < BasicObject
def self.underscore(string)
- string.gsub(/([A-Z]+)([A-Z][a-z])/,'\1_\2').gsub(/([a-z])([A-Z])/,'\1_\2').downcase
+ string.gsub(/([A-Z]+)([A-Z][a-z])/, '\1_\2').gsub(/([a-z])([A-Z])/, '\1_\2').downcase
end
attr_reader :request, :response, :body, :headers
- def initialize(request, response, parsed_block, options={})
+ def initialize(request, response, parsed_block, options = {})
@request = request
@response = response
@body = options[:body] || response.body
@@ -37,7 +37,7 @@ def tap
end
def inspect
- inspect_id = "%x" % (object_id * 2)
+ inspect_id = format "%x", (object_id * 2)
%(#<#{self.class}:0x#{inspect_id} parsed_response=#{parsed_response.inspect}, @response=#{response.inspect}, @headers=#{headers.inspect}>)
end
View
2  spec/httparty/connection_adapter_spec.rb
@@ -1,7 +1,6 @@
require File.expand_path(File.join(File.dirname(__FILE__), '..', 'spec_helper'))
RSpec.describe HTTParty::ConnectionAdapter do
-
describe "initialization" do
let(:uri) { URI 'http://www.google.com' }
it "takes a URI as input" do
@@ -94,7 +93,6 @@
it { is_expected.to use_ssl }
end
-
context "when ssl version is set" do
let(:options) { {ssl_version: :TLSv1} }
View
10 spec/httparty/cookie_hash_spec.rb
@@ -37,17 +37,17 @@
end
it "should handle '=' within cookie value" do
- @cookie_hash.add_cookies("first=one=1; second=two=2==")
- expect(@cookie_hash.keys).to include(:first, :second)
- expect(@cookie_hash[:first]).to eq('one=1')
- expect(@cookie_hash[:second]).to eq('two=2==')
+ @cookie_hash.add_cookies("first=one=1; second=two=2==")
+ expect(@cookie_hash.keys).to include(:first, :second)
+ expect(@cookie_hash[:first]).to eq('one=1')
+ expect(@cookie_hash[:second]).to eq('two=2==')
end
end
describe 'with other class' do
it "should error" do
expect {
- @cookie_hash.add_cookies(Array.new)
+ @cookie_hash.add_cookies([])
}.to raise_error
end
end
View
2  spec/httparty/exception_spec.rb
@@ -14,7 +14,7 @@
it { is_expected.to include(HTTParty::Error) }
end
end
-
+
describe HTTParty::UnsupportedURIScheme do
describe '#ancestors' do
subject { super().ancestors }
View
6 spec/httparty/logger/logger_spec.rb
@@ -5,17 +5,17 @@
subject { HTTParty::Logger }
it "defaults level to :info" do
- logger_double = double()
+ logger_double = double
expect(subject.build(logger_double, nil, nil).level).to eq(:info)
end
it "defaults format to :apache" do
- logger_double = double()
+ logger_double = double
expect(subject.build(logger_double, nil, nil)).to be_an_instance_of(HTTParty::Logger::ApacheLogger)
end
it "builds :curl style logger" do
- logger_double = double()
+ logger_double = double
expect(subject.build(logger_double, nil, :curl)).to be_an_instance_of(HTTParty::Logger::CurlLogger)
end
end
View
52 spec/httparty/net_digest_auth_spec.rb
@@ -3,7 +3,7 @@
RSpec.describe Net::HTTPHeader::DigestAuthenticator do
def setup_digest(response)
digest = Net::HTTPHeader::DigestAuthenticator.new("Mufasa",
- "Circle Of Life", "GET", "/dir/index.html", response)
+ "Circle Of Life", "GET", "/dir/index.html", response)
allow(digest).to receive(:random).and_return("deadbeef")
allow(Digest::MD5).to receive(:hexdigest) { |str| "md5(#{str})" }
digest
@@ -50,7 +50,7 @@ def cookie_header
end
it "should set opaque" do
- expect(authorization_header).to include(%Q(opaque="solid"))
+ expect(authorization_header).to include('opaque="solid"')
end
end
@@ -62,14 +62,14 @@ def cookie_header
end
it "should not set opaque" do
- expect(authorization_header).not_to include(%Q(opaque=))
+ expect(authorization_header).not_to include("opaque=")
end
end
context "with specified quality of protection (qop)" do
before do
@digest = setup_digest({
- 'www-authenticate' => 'Digest realm="myhost@testrealm.com", nonce="NONCE", qop="auth"',
+ 'www-authenticate' => 'Digest realm="myhost@testrealm.com", nonce="NONCE", qop="auth"'
})
end
@@ -78,47 +78,47 @@ def cookie_header
end
it "should set username" do
- expect(authorization_header).to include(%Q(username="Mufasa"))
+ expect(authorization_header).to include('username="Mufasa"')
end
it "should set digest-uri" do
- expect(authorization_header).to include(%Q(uri="/dir/index.html"))
+ expect(authorization_header).to include('uri="/dir/index.html"')
end
it "should set qop" do
- expect(authorization_header).to include(%Q(qop="auth"))
+ expect(authorization_header).to include('qop="auth"')
end
it "should set cnonce" do
- expect(authorization_header).to include(%Q(cnonce="md5(deadbeef)"))
+ expect(authorization_header).to include('cnonce="md5(deadbeef)"')
end
it "should set nonce-count" do
- expect(authorization_header).to include(%Q(nc=00000001))
+ expect(authorization_header).to include("nc=00000001")
end
it "should set response" do
request_digest = "md5(md5(Mufasa:myhost@testrealm.com:Circle Of Life):NONCE:00000001:md5(deadbeef):auth:md5(GET:/dir/index.html))"
- expect(authorization_header).to include(%Q(response="#{request_digest}"))
+ expect(authorization_header).to include(%(response="#{request_digest}"))
end
end
context "when quality of protection (qop) is unquoted" do
before do
@digest = setup_digest({
- 'www-authenticate' => 'Digest realm="myhost@testrealm.com", nonce="NONCE", qop=auth',
+ 'www-authenticate' => 'Digest realm="myhost@testrealm.com", nonce="NONCE", qop=auth'
})
end
it "should still set qop" do
- expect(authorization_header).to include(%Q(qop="auth"))
+ expect(authorization_header).to include('qop="auth"')
end
end
context "with unspecified quality of protection (qop)" do
before do
@digest = setup_digest({
- 'www-authenticate' => 'Digest realm="myhost@testrealm.com", nonce="NONCE"',
+ 'www-authenticate' => 'Digest realm="myhost@testrealm.com", nonce="NONCE"'
})
end
@@ -127,35 +127,35 @@ def cookie_header
end
it "should set username" do
- expect(authorization_header).to include(%Q(username="Mufasa"))
+ expect(authorization_header).to include('username="Mufasa"')
end
it "should set digest-uri" do
- expect(authorization_header).to include(%Q(uri="/dir/index.html"))
+ expect(authorization_header).to include('uri="/dir/index.html"')
end
it "should not set qop" do
- expect(authorization_header).not_to include(%Q(qop=))
+ expect(authorization_header).not_to include("qop=")
end
it "should not set cnonce" do
- expect(authorization_header).not_to include(%Q(cnonce=))
+ expect(authorization_header).not_to include("cnonce=")
end
it "should not set nonce-count" do
- expect(authorization_header).not_to include(%Q(nc=))
+ expect(authorization_header).not_to include("nc=")
end
it "should set response" do
request_digest = "md5(md5(Mufasa:myhost@testrealm.com:Circle Of Life):NONCE:md5(GET:/dir/index.html))"
- expect(authorization_header).to include(%Q(response="#{request_digest}"))
+ expect(authorization_header).to include(%(response="#{request_digest}"))
end
end
context "with multiple authenticate headers" do
before do
@digest = setup_digest({
- 'www-authenticate' => 'NTLM, Digest realm="myhost@testrealm.com", nonce="NONCE", qop="auth"',
+ 'www-authenticate' => 'NTLM, Digest realm="myhost@testrealm.com", nonce="NONCE", qop="auth"'
})
end
@@ -164,28 +164,28 @@ def cookie_header
end
it "should set username" do
- expect(authorization_header).to include(%Q(username="Mufasa"))
+ expect(authorization_header).to include('username="Mufasa"')
end
it "should set digest-uri" do
- expect(authorization_header).to include(%Q(uri="/dir/index.html"))
+ expect(authorization_header).to include('uri="/dir/index.html"')
end
it "should set qop" do
- expect(authorization_header).to include(%Q(qop="auth"))
+ expect(authorization_header).to include('qop="auth"')
end
it "should set cnonce" do
- expect(authorization_header).to include(%Q(cnonce="md5(deadbeef)"))
+ expect(authorization_header).to include('cnonce="md5(deadbeef)"')
end
it "should set nonce-count" do
- expect(authorization_header).to include(%Q(nc=00000001))
+ expect(authorization_header).to include("nc=00000001")
end
it "should set response" do
request_digest = "md5(md5(Mufasa:myhost@testrealm.com:Circle Of Life):NONCE:00000001:md5(deadbeef):auth:md5(GET:/dir/index.html))"
- expect(authorization_header).to include(%Q(response="#{request_digest}"))
+ expect(authorization_header).to include(%(response="#{request_digest}"))
end
end
end
View
4 spec/httparty/parser_spec.rb
@@ -124,7 +124,9 @@ class MyParser < HTTParty::Parser
it "raises a useful exception message for subclasses" do
atom_parser = Class.new(HTTParty::Parser) do
- def self.name; 'AtomParser'; end
+ def self.name
+ 'AtomParser'
+ end
end
parser = atom_parser.new 'body', :atom
expect do
View
42 spec/httparty/request_spec.rb
@@ -14,7 +14,6 @@
end
context "when the query is an array" do
-
it "doesn't include brackets" do
query_string = normalizer[{page: 1, foo: %w(bar baz)}]
expect(CGI.unescape(query_string)).to eq("foo=bar&foo=baz&page=1")
@@ -61,15 +60,15 @@
context "when basic auth options wasn't set explicitly" do
it "sets basic auth from uri" do
request = HTTParty::Request.new(Net::HTTP::Get, 'http://user1:pass1@example.com')
- expect(request.options[:basic_auth]).to eq({:username => 'user1', :password => 'pass1'})
+ expect(request.options[:basic_auth]).to eq({username: 'user1', password: 'pass1'})
end
end
context "when basic auth options was set explicitly" do
it "uses basic auth from url anyway" do
- basic_auth = {:username => 'user2', :password => 'pass2'}
- request = HTTParty::Request.new(Net::HTTP::Get, 'http://user1:pass1@example.com', :basic_auth => basic_auth)
- expect(request.options[:basic_auth]).to eq({:username => 'user1', :password => 'pass1'})
+ basic_auth = {username: 'user2', password: 'pass2'}
+ request = HTTParty::Request.new(Net::HTTP::Get, 'http://user1:pass1@example.com', basic_auth: basic_auth)
+ expect(request.options[:basic_auth]).to eq({username: 'user1', password: 'pass1'})
end
end
end
@@ -103,7 +102,6 @@
expect(request.format).to eq(:json)
end
end
-
end
context "options" do
@@ -115,7 +113,7 @@
it "should use digest auth when configured" do
FakeWeb.register_uri(:get, "http://api.foo.com/v1",
- www_authenticate: 'Digest realm="Log Viewer", qop="auth", nonce="2CA0EC6B0E126C4800E56BA0C0003D3C", opaque="5ccc069c403ebaf9f0171e9517f40e41", stale=false')
+ www_authenticate: 'Digest realm="Log Viewer", qop="auth", nonce="2CA0EC6B0E126C4800E56BA0C0003D3C", opaque="5ccc069c403ebaf9f0171e9517f40e41", stale=false')
@request.options[:digest_auth] = {username: 'foobar', password: 'secret'}
@request.send(:setup_raw_request)
@@ -239,7 +237,6 @@
expect(CGI.unescape(@request.uri.query)).to eq("foo[]=bar&foo[]=baz")
end
end
-
end
end
@@ -332,19 +329,19 @@
describe 'parsing responses' do
it 'should handle xml automatically' do
- xml = %q[<books><book><id>1234</id><name>Foo Bar!</name></book></books>]
+ xml = '<books><book><id>1234</id><name>Foo Bar!</name></book></books>'
@request.options[:format] = :xml
expect(@request.send(:parse_response, xml)).to eq({'books' => {'book' => {'id' => '1234', 'name' => 'Foo Bar!'}}})
end
it 'should handle csv automatically' do
- csv=[%q["id","Name"],%q["1234","Foo Bar!"]].join("\n")
+ csv = ['"id","Name"', '"1234","Foo Bar!"'].join("\n")
@request.options[:format] = :csv
- expect(@request.send(:parse_response, csv)).to eq([["id","Name"],["1234","Foo Bar!"]])
+ expect(@request.send(:parse_response, csv)).to eq([%w(id Name), ["1234", "Foo Bar!"]])
end
it 'should handle json automatically' do
- json = %q[{"books": {"book": {"name": "Foo Bar!", "id": "1234"}}}]
+ json = '{"books": {"book": {"name": "Foo Bar!", "id": "1234"}}}'
@request.options[:format] = :json
expect(@request.send(:parse_response, json)).to eq({'books' => {'book' => {'id' => '1234', 'name' => 'Foo Bar!'}}})
end
@@ -407,9 +404,7 @@
expect(resp.body.encoding).to eq(Encoding.find("UTF-16LE"))
end
-
it "should perform no encoding if the charset is not available" do
-
response = stub_response "Content"
response.initialize_http_header("Content-Type" => "text/plain;charset = utf-lols")
resp = @request.perform
@@ -418,7 +413,6 @@
end
it "should perform no encoding if the content type is specified but no charset is specified" do
-
response = stub_response "Content"
response.initialize_http_header("Content-Type" => "text/plain")
resp = @request.perform
@@ -599,14 +593,14 @@
end
it 'should update cookies with rediects' do
- @request.options[:headers] = {'Cookie'=> 'foo=bar;'}
+ @request.options[:headers] = {'Cookie' => 'foo=bar;'}
@redirect['Set-Cookie'] = 'foo=tar;'
@request.perform
expect(@request.options[:headers]['Cookie']).to match(/foo=tar/)
end
it 'should keep cookies between rediects' do
- @request.options[:headers] = {'Cookie'=> 'keep=me'}
+ @request.options[:headers] = {'Cookie' => 'keep=me'}
@redirect['Set-Cookie'] = 'foo=tar;'
@request.perform
expect(@request.options[:headers]['Cookie']).to match(/keep=me/)
@@ -719,14 +713,14 @@
end
it 'should update cookies with rediects' do
- @request.options[:headers] = {'Cookie'=> 'foo=bar;'}
+ @request.options[:headers] = {'Cookie' => 'foo=bar;'}
@redirect['Set-Cookie'] = 'foo=tar;'
@request.perform
expect(@request.options[:headers]['Cookie']).to match(/foo=tar/)
end
it 'should keep cookies between rediects' do
- @request.options[:headers] = {'Cookie'=> 'keep=me'}
+ @request.options[:headers] = {'Cookie' => 'keep=me'}
@redirect['Set-Cookie'] = 'foo=tar;'
@request.perform
expect(@request.options[:headers]['Cookie']).to match(/keep=me/)
@@ -794,7 +788,7 @@
context "context-encoding" do
before do
@request.options[:format] = :html
- @last_response = double()
+ @last_response = double
allow(@last_response).to receive(:body).and_return('')
end
@@ -841,19 +835,19 @@
it "should raise argument error if basic_auth is not a hash" do
expect {
- HTTParty::Request.new(Net::HTTP::Post, 'http://api.foo.com/v1', basic_auth: ["foo", "bar"]).perform
+ HTTParty::Request.new(Net::HTTP::Post, 'http://api.foo.com/v1', basic_auth: %w(foo bar)).perform
}.to raise_error(ArgumentError, ":basic_auth must be a hash")
end
it "should raise argument error if digest_auth is not a hash" do
expect {
- HTTParty::Request.new(Net::HTTP::Post, 'http://api.foo.com/v1', digest_auth: ["foo", "bar"]).perform
+ HTTParty::Request.new(Net::HTTP::Post, 'http://api.foo.com/v1', digest_auth: %w(foo bar)).perform
}.to raise_error(ArgumentError, ":digest_auth must be a hash")
end
it "should raise argument error if headers is not a hash" do
expect {
- HTTParty::Request.new(Net::HTTP::Post, 'http://api.foo.com/v1', headers: ["foo", "bar"]).perform
+ HTTParty::Request.new(Net::HTTP::Post, 'http://api.foo.com/v1', headers: %w(foo bar)).perform
}.to raise_error(ArgumentError, ":headers must be a hash")
end
@@ -871,7 +865,7 @@
it "should raise RedirectionTooDeep error if limit is negative" do
expect {
- HTTParty::Request.new(Net::HTTP::Post, 'http://api.foo.com/v1', limit: -1).perform
+ HTTParty::Request.new(Net::HTTP::Post, 'http://api.foo.com/v1', limit: -1).perform
}.to raise_error(HTTParty::RedirectionTooDeep, 'HTTP redirects too deep')
end
end
View
20 spec/httparty_spec.rb
@@ -123,7 +123,7 @@
end
describe "headers" do
- def expect_headers(header={})
+ def expect_headers(header = {})
expect(HTTParty::Request).to receive(:new) \
.with(anything, anything, hash_including({ headers: header })) \
.and_return(double("mock response", perform: nil))
@@ -313,12 +313,12 @@ def second_method
describe "parser" do
class CustomParser
def self.parse(body)
- return {sexy: true}
+ {sexy: true}
end
end
let(:parser) do
- Proc.new{ |data, format| CustomParser.parse(data) }
+ proc { |data, format| CustomParser.parse(data) }
end
it "should set parser options" do
@@ -373,9 +373,9 @@ class MyParser < HTTParty::Parser
it "should process a request with a connection from the adapter" do
connection_adapter_options = {foo: :bar}
- expect(connection_adapter).to receive(:call) { |u,o|
+ expect(connection_adapter).to receive(:call) { |u, o|
expect(o[:connection_adapter_options]).to eq(connection_adapter_options)
- HTTParty::ConnectionAdapter.call(u,o)
+ HTTParty::ConnectionAdapter.call(u, o)
}.with(URI.parse(uri), kind_of(Hash))
FakeWeb.register_uri(:get, uri, body: 'stuff')
@klass.connection_adapter connection_adapter, connection_adapter_options
@@ -676,7 +676,7 @@ def self.inherited(subclass)
end
it "should be able to get chunked html" do
- chunks = ["Chunk1", "Chunk2", "Chunk3", "Chunk4"]
+ chunks = %w(Chunk1 Chunk2 Chunk3 Chunk4)
stub_chunked_http_response_with(chunks)
expect(
@@ -687,7 +687,7 @@ def self.inherited(subclass)
end
it "should return an empty body if stream_body option is turned on" do
- chunks = ["Chunk1", "Chunk2", "Chunk3", "Chunk4"]
+ chunks = %w(Chunk1 Chunk2 Chunk3 Chunk4)
options = {stream_body: true, format: 'html'}
stub_chunked_http_response_with(chunks, options)
@@ -736,14 +736,14 @@ def self.inherited(subclass)
stub_http_response_with('twitter.csv')
profile = HTTParty.get('http://twitter.com/statuses/profile.csv')
expect(profile.size).to eq(2)
- expect(profile[0]).to eq(["name","url","id","description","protected","screen_name","followers_count","profile_image_url","location"])
- expect(profile[1]).to eq(["Magic 8 Bot",nil,"17656026","ask me a question","false","magic8bot","90","http://s3.amazonaws.com/twitter_production/profile_images/65565851/8ball_large_normal.jpg",nil])
+ expect(profile[0]).to eq(%w(name url id description protected screen_name followers_count profile_image_url location))
+ expect(profile[1]).to eq(["Magic 8 Bot", nil, "17656026", "ask me a question", "false", "magic8bot", "90", "http://s3.amazonaws.com/twitter_production/profile_images/65565851/8ball_large_normal.jpg", nil])
end
it "should not get undefined method add_node for nil class for the following xml" do
stub_http_response_with('undefined_method_add_node_for_nil.xml')
result = HTTParty.get('http://foobar.com')
- expect(result.parsed_response).to eq({"Entities"=>{"href"=>"https://s3-sandbox.parature.com/api/v1/5578/5633/Account", "results"=>"0", "total"=>"0", "page_size"=>"25", "page"=>"1"}})
+ expect(result.parsed_response).to eq({"Entities" => {"href" => "https://s3-sandbox.parature.com/api/v1/5578/5633/Account", "results" => "0", "total" => "0", "page_size" => "25", "page" => "1"}})
end
it "should parse empty response fine" do
View
9 spec/spec_helper.rb
@@ -1,15 +1,14 @@
require "simplecov"
SimpleCov.start
-
require "httparty"
require "fakeweb"
def file_fixture(filename)
- open(File.join(File.dirname(__FILE__), 'fixtures', "#{filename.to_s}")).read
+ open(File.join(File.dirname(__FILE__), 'fixtures', "#{filename}")).read
end
-Dir[File.expand_path(File.join(File.dirname(__FILE__),'support','**','*.rb'))].each {|f| require f}
+Dir[File.expand_path(File.join(File.dirname(__FILE__), 'support', '**', '*.rb'))].each {|f| require f}
RSpec.configure do |config|
config.include HTTParty::StubResponse
@@ -50,9 +49,7 @@ def file_fixture(filename)
end
RSpec::Matchers.define :use_ssl do
- match do |connection|
- connection.use_ssl?
- end
+ match(&:use_ssl?)
end
RSpec::Matchers.define :use_cert_store do |cert_store|
View
4 spec/support/ssl_test_helper.rb
@@ -5,7 +5,7 @@ module SSLTestHelper
def ssl_verify_test(mode, ca_basename, server_cert_filename, options = {})
options = {
format: :json,
- timeout: 30,
+ timeout: 30
}.merge(options)
if mode
@@ -34,7 +34,7 @@ def ssl_verify_test(mode, ca_basename, server_cert_filename, options = {})
test_server = SSLTestServer.new({
rsa_key: path.join('server.key').read,
- cert: path.join(server_cert_filename).read,
+ cert: path.join(server_cert_filename).read
})
test_server.start
View
42 spec/support/ssl_test_server.rb
@@ -9,7 +9,7 @@ class SSLTestServer
attr_accessor :ctx # SSLContext object
attr_reader :port
- def initialize(options={})
+ def initialize(options = {})
@ctx = OpenSSL::SSL::SSLContext.new
@ctx.cert = OpenSSL::X509::Certificate.new(options[:cert])
@ctx.key = OpenSSL::PKey::RSA.new(options[:rsa_key])
@@ -24,21 +24,21 @@ def start
@raw_server = TCPServer.new(@port)
if @port == 0
- @port = Socket::getnameinfo(@raw_server.getsockname, Socket::NI_NUMERICHOST|Socket::NI_NUMERICSERV)[1].to_i
+ @port = Socket.getnameinfo(@raw_server.getsockname, Socket::NI_NUMERICHOST | Socket::NI_NUMERICSERV)[1].to_i
end
@ssl_server = OpenSSL::SSL::SSLServer.new(@raw_server, @ctx)
- @stopping_mutex.synchronize{
+ @stopping_mutex.synchronize {
return if @stopping
- @thread = Thread.new{ thread_main }
+ @thread = Thread.new { thread_main }
}
nil
end
def stop
- @stopping_mutex.synchronize{
+ @stopping_mutex.synchronize {
return if @stopping
@stopping = true
}
@@ -47,22 +47,22 @@ def stop
private
- def thread_main
- until @stopping_mutex.synchronize{ @stopping }
- (rr,_,_) = select([@ssl_server.to_io], nil, nil, 0.1)
+ def thread_main
+ until @stopping_mutex.synchronize { @stopping }
+ (rr, _, _) = select([@ssl_server.to_io], nil, nil, 0.1)
- next unless rr && rr.include?(@ssl_server.to_io)
+ next unless rr && rr.include?(@ssl_server.to_io)
- socket = @ssl_server.accept
+ socket = @ssl_server.accept
- Thread.new{
- header = []
+ Thread.new {
+ header = []
- until (line = socket.readline).rstrip.empty?
- header << line
- end
+ until (line = socket.readline).rstrip.empty?
+ header << line
+ end
- response =<<EOF
+ response = <<EOF
HTTP/1.1 200 OK
Connection: close
Content-Type: application/json; charset=UTF-8
@@ -70,11 +70,11 @@ def thread_main
{"success":true}
EOF
- socket.write(response.gsub(/\r\n/n, "\n").gsub(/\n/n, "\r\n"))
- socket.close
+ socket.write(response.gsub(/\r\n/n, "\n").gsub(/\n/n, "\r\n"))
+ socket.close
}
- end
-
- @ssl_server.close
end
+
+ @ssl_server.close
+ end
end
View
2  spec/support/stub_response.rb
@@ -13,7 +13,7 @@ def stub_http_response_with(filename)
expect(HTTParty::Request).to receive(:new).and_return(http_request)
end
- def stub_chunked_http_response_with(chunks, options={format: "html"})
+ def stub_chunked_http_response_with(chunks, options = {format: "html"})
response = Net::HTTPResponse.new("1.1", 200, nil)
allow(response).to receive(:chunked_data).and_return(chunks)
def response.read_body(&block)
Please sign in to comment.
Something went wrong with that request. Please try again.