Skip to content

Instantly share code, notes, and snippets.

@cu39
Created May 25, 2013 07:28
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save cu39/5648264 to your computer and use it in GitHub Desktop.
Save cu39/5648264 to your computer and use it in GitHub Desktop.
Tell the constructor new settings in your own DSL. `WhateverService` is a toplevel module whose `configure` method returns `WhateverService::Client` when a block passed. This config block is going to be `instance_eval`-ed in `WhateverService::Client`'s constructor. You can also pass a hash to the `WhateverService::Client`'s constructor.
$: << '.'
require 'whatever_service'
wsc1 = WhateverService.configure do
user_id 'foo'
password 'bar_baz'
end
wsc2 = WhateverService::Client.new(:user_id => 'baz', :password => 'foo_bar')
[wsc1, wsc2].each do |w|
WhateverService::Client::CONFIG_NAMES.each do |name|
puts "#{name} = #{w.config[name]}"
end
end
# output:
# user_id = foo
# password = bar_baz
# user_id = baz
# password = foo_bar
module WhateverService
# WS_DIR = File.expand_path(File.dirname(__FILE__))
#
# %w(client).each do |sub|
# require File.join(WS_DIR, 'whatever_service', sub)
# end
def self.configure(&blk)
WhateverService::Client.new &blk
end
end
# the following should be in whatever_service/client.rb
# but is here for Gist restriction
module WhateverService
class Client
CONFIG_NAMES = [:user_id, :password]
CONFIG_NAMES.each do |name|
define_method(name) { |val| @config[name] = val }
end
attr_reader :config
def initialize(options = {}, &blk)
@config = options
instance_eval &blk unless blk.nil?
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment