Skip to content

Commit

Permalink
encapsulate the common require-rescue-load_error pattern for middlewa…
Browse files Browse the repository at this point in the history
…re dependencies
  • Loading branch information
mislav committed Mar 28, 2011
1 parent c683c44 commit 82055b6
Show file tree
Hide file tree
Showing 6 changed files with 12 additions and 21 deletions.
4 changes: 1 addition & 3 deletions lib/faraday/adapter/em_synchrony.rb
@@ -1,11 +1,9 @@
module Faraday
class Adapter
class EMSynchrony < Faraday::Adapter
begin
dependency do
require 'em-synchrony/em-http'
require 'fiber'
rescue LoadError, NameError => e
self.load_error = e
end

def call(env)
Expand Down
6 changes: 1 addition & 5 deletions lib/faraday/adapter/excon.rb
@@ -1,11 +1,7 @@
module Faraday
class Adapter
class Excon < Faraday::Adapter
begin
require 'excon'
rescue LoadError, NameError => e
self.load_error = e
end
dependency 'excon'

def call(env)
super
Expand Down
6 changes: 1 addition & 5 deletions lib/faraday/adapter/patron.rb
@@ -1,11 +1,7 @@
module Faraday
class Adapter
class Patron < Faraday::Adapter
begin
require 'patron'
rescue LoadError, NameError => e
self.load_error = e
end
dependency 'patron'

def call(env)
super
Expand Down
6 changes: 1 addition & 5 deletions lib/faraday/adapter/typhoeus.rb
Expand Up @@ -7,11 +7,7 @@ def self.setup_parallel_manager(options = {})
options.empty? ? ::Typhoeus::Hydra.hydra : ::Typhoeus::Hydra.new(options)
end

begin
require 'typhoeus'
rescue LoadError, NameError => e
self.load_error = e
end
dependency 'typhoeus'

def call(env)
super
Expand Down
7 changes: 7 additions & 0 deletions lib/faraday/middleware.rb
Expand Up @@ -11,6 +11,13 @@ def setup_parallel_manager(options = {})
end
end

# Executes a block which should try to require and reference dependent libraries
def self.dependency(lib = nil)
lib ? require(lib) : yield
rescue LoadError, NameError => error
self.load_error = error
end

def self.loaded?
@load_error.nil?
end
Expand Down
4 changes: 1 addition & 3 deletions lib/faraday/request/json.rb
Expand Up @@ -7,7 +7,7 @@ class << self
end

# loads the JSON encoder either from yajl-ruby or activesupport
begin
dependency do
begin
require 'yajl'
self.adapter = Yajl::Encoder
Expand All @@ -18,8 +18,6 @@ class << self
require 'active_support/ordered_hash' # AS 3.0.4
self.adapter = ActiveSupport::JSON
end
rescue LoadError, NameError => error
self.load_error = error
end

def call(env)
Expand Down

0 comments on commit 82055b6

Please sign in to comment.