lib/nsisam/client.rb in nsisam-0.3.4 vs lib/nsisam/client.rb in nsisam-0.4.0
- old
+ new
@@ -1,24 +1,28 @@
require "json"
require "net/http"
require "digest"
+
+require File.dirname(__FILE__) + '/configuration'
require File.dirname(__FILE__) + '/errors'
module NSISam
class Client
# Initialize a client to a SAM node hosted at a specific url
#
- # @param [String] url the SAM node url
+ # @param [Hash] optional hash with user, password, host and port of the SAM node
# @return [Client] the object itself
# @example
- # nsisam = NSISam::Client.new 'http://user:pass@ip:port/'
- def initialize(url)
- user_and_pass = url.match(/(\w+):(\w+)/)
- @user, @password = user_and_pass[1], user_and_pass[2]
- @url = url.match(/@(.*):/)[1]
- @port = url.match(/([0-9]+)(\/)?$/)[1]
+ # nsisam = NSISam::Client.new user: 'username' password: 'pass',
+ # host: 'localhost', port: '8888'
+ def initialize(params = {})
+ params = Configuration.settings.merge(params)
+ @user = params[:user]
+ @password = params[:password]
+ @host = params[:host]
+ @port = params[:port]
end
# Store a given data in SAM
#
# @param [String] data the desired data to store
@@ -91,10 +95,25 @@
request_data = {:key => key, :value => value}.to_json
request = prepare_request :POST, request_data
execute_request(request)
end
+ # Configure the default values for NSISam::Client objects
+ #
+ # @param [Block]
+ #
+ # @example
+ # NSISam::Client.configure do
+ # user "why"
+ # password "chunky"
+ # host "localhost"
+ # port "8888"
+ # end
+ def self.configure(&block)
+ Configuration.instance_eval(&block)
+ end
+
private
def prepare_request(verb, body)
verb = verb.to_s.capitalize!
request = Net::HTTP.const_get("#{verb}").new '/'
@@ -103,10 +122,10 @@
request
end
def execute_request(request)
begin
- response = Net::HTTP.start @url, @port do |http|
+ response = Net::HTTP.start @host, @port do |http|
http.request(request)
end
rescue Errno::ECONNREFUSED => e
raise NSISam::Errors::Client::ConnectionRefusedError
else