Class: Restfully::Session

Inherits:
Object
  • Object
show all
Defined in:
lib/restfully/session.rb

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(options = {}) {|root, _self| ... } ⇒ Session

Builds a new client session. Takes a number of options as input. Yields or return the root Restfully::Resource object, and the Restfully::Session object.

:configuration_file

the location of a YAML configuration file that contains any of the parameters below.

:uri

the entry-point URI for this session.

:logger

a Logger object, used to display information.

:require

an Array of Restfully::MediaType objects to automatically require for this session.

:retry_on_error

the maximum number of attempts to make when a server (502,502,504) or connection error occurs.

:wait_before_retry

the number of seconds to wait before making another attempt when a server or connection error occurs.

:default_headers

a Hash of default HTTP headers to send with each request.

:cache

a Hash of parameters to configure the caching component. See <rtomayko.github.com/rack-cache/configuration> for more information.

e.g.

Restfully::Session.new(
  :uri => "https://api.bonfire-project.eu:444/",
  :username => "crohr",
  :password => "PASSWORD",
  :require => ['ApplicationVndBonfireXml']
) {|root, session| p root}

Yields:

Yield Parameters:



45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
# File 'lib/restfully/session.rb', line 45

def initialize(options = {})
  @config = if options.kind_of?(Configuration)
    options
  else
    Configuration.new(options).expand
  end

  setup
  
  #similar to 
  # @ssl_options=config.to_hash.select{|k,v| k =~ /^ssl/ || k =~ /verify_ssl/}
  #but supporting the retarded ruby 1.8.7 of select (output an Array)
  @ssl_options=Hash[*config.to_hash.select{|k,v| k =~ /^ssl/ || k =~ /verify_ssl/}.flatten]
 
  yield root, self if block_given?
end

Instance Attribute Details

#configObject (readonly)

Returns the value of attribute config.



16
17
18
# File 'lib/restfully/session.rb', line 16

def config
  @config
end

#default_headersObject

Return the Hash of default HTTP headers that are sent with each request.



140
141
142
143
144
145
146
# File 'lib/restfully/session.rb', line 140

def default_headers
  @default_headers ||= {
    'Accept' => '*/*',
    'Accept-Encoding' => 'gzip, deflate',
    'User-Agent' => "Restfully/#{Restfully::VERSION}" 
  }
end

#ssl_optionsObject (readonly)

Returns the value of attribute ssl_options.



18
19
20
# File 'lib/restfully/session.rb', line 18

def ssl_options
  @ssl_options
end

#uriObject

Returns the value of attribute uri.



15
16
17
# File 'lib/restfully/session.rb', line 15

def uri
  @uri
end

Instance Method Details

#authenticate(options = {}) ⇒ Object

Authnenticates the request using Basic Authentication.



124
125
126
127
128
129
130
131
132
# File 'lib/restfully/session.rb', line 124

def authenticate(options = {})
  if options[:username]
    enable(
      Restfully::Rack::BasicAuth,
      options[:username],
      options[:password]
    )
  end
end

#delete(path, options = {}) ⇒ Object

Returns an HTTP::Response object or raise a Restfully::HTTP::Error



182
183
184
# File 'lib/restfully/session.rb', line 182

def delete(path, options = {})
  transmit :delete, path, options
end

#disable(rack, *args) ⇒ Object

Disable a RestClient Rack component.



112
113
114
115
# File 'lib/restfully/session.rb', line 112

def disable(rack, *args)
  logger.info "Disabling #{rack.inspect}."
  RestClient.disable rack, *args
end

#enable(rack, *args) ⇒ Object

Enable a RestClient Rack component.



106
107
108
109
# File 'lib/restfully/session.rb', line 106

def enable(rack, *args)
  logger.info "Enabling #{rack.inspect}."
  RestClient.enable rack, *args
end

#get(path, options = {}) ⇒ Object

Returns an HTTP::Response object or raise a Restfully::HTTP::Error



165
166
167
# File 'lib/restfully/session.rb', line 165

def get(path, options = {})
  transmit :get, path, options
end

#head(path, options = {}) ⇒ Object

Returns an HTTP::Response object or raise a Restfully::HTTP::Error



160
161
162
# File 'lib/restfully/session.rb', line 160

def head(path, options = {})
  transmit :head, path, options
end

#loggerObject



20
21
22
# File 'lib/restfully/session.rb', line 20

def logger
  @config.logger
end

#middlewareObject

Returns the list of middleware components enabled. See rest-client-components for more information.



119
120
121
# File 'lib/restfully/session.rb', line 119

def middleware
  RestClient.components.map{|(rack, args)| rack}
end

#post(path, body, options = {}) ⇒ Object

Returns an HTTP::Response object or raise a Restfully::HTTP::Error



170
171
172
173
# File 'lib/restfully/session.rb', line 170

def post(path, body, options = {})
  options[:body] = body
  transmit :post, path, options
end

#process(response, request) ⇒ Object

Process a Restfully::HTTP::Response.



187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
# File 'lib/restfully/session.rb', line 187

def process(response, request)
  case code=response.code
  when 200
    logger.debug "Building response..."
    Resource.new(self, response, request).build
  when 201,202
    logger.debug "Getting description of newly created resource at: #{response.head['Location'].inspect}"
    get response.head['Location'], :head => request.head
  when 301,302
    logger.debug "Following redirection to: #{response.head['Location'].inspect}"
    get response.head['Location'], :head => request.head
  when 204
    true
  when 400..499
    raise HTTP::ClientError, error_message(request, response)
  when 502..504
    if res = request.retry!
      process(res, request)
    else
     raise(HTTP::ServerError, error_message(request, response))
   end
  when 500, 501
    raise HTTP::ServerError, error_message(request, response)
  else
    raise Error, "Restfully does not handle code #{code.inspect}."
  end
end

#put(path, body, options = {}) ⇒ Object

Returns an HTTP::Response object or raise a Restfully::HTTP::Error



176
177
178
179
# File 'lib/restfully/session.rb', line 176

def put(path, body, options = {})
  options[:body] = body
  transmit :put, path, options
end

#rootObject

Returns the root Restfully::Resource.



149
150
151
# File 'lib/restfully/session.rb', line 149

def root
  get(uri.path).load
end

#sandboxObject

Return a sandbox object, useful to execute code within the current session context witout polluting the Session object.



155
156
157
# File 'lib/restfully/session.rb', line 155

def sandbox
  Sandbox.new(self)
end

#setupObject



62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
# File 'lib/restfully/session.rb', line 62

def setup
  # Compatibility with :base_uri parameter of Restfully <= 0.6
  @uri = config[:uri] || config[:base_uri]
  msg = if @uri.nil? || @uri.empty?
    @uri = Restfully::DEFAULT_URI
    "No URI given. Using #{@uri}"
  else
    "Base URI changed to: #{@uri}" 
  end
  if config[:overridden] || @uri == Restfully::DEFAULT_URI
    config[:shell] ? puts(msg) : logger.warn(msg)
  end

  @uri = Addressable::URI.parse(@uri)

  default_headers.merge!(config[:default_headers] || {})

  disable RestClient::Rack::Compatibility
  authenticate(config)
  setup_cache(config[:cache])

  # Require additional types (e.g.: media-types):
  (config[:require] || []).each do |r|
    logger.info "Requiring #{r}..."
    if ::File.exist?(file=File.expand_path(r))
      require file
    elsif r =~ /^https?:\/\//i
      begin
        resource = get(r)
        file = Tempfile.new(['restfully', '.rb'])
        file << resource.response.body
        file.close
        require file.path.gsub(/\.rb^/,'')
      rescue HTTP::Error => e
        logger.fatal "Can't fetch #{r} from the Internet. Aborting."
        raise e
      end
    else
      require "restfully/media_type/#{r.underscore}"
    end
  end
end

#uri_to(path) ⇒ Object

Builds the complete URI, based on the given path and the session’s uri



135
136
137
# File 'lib/restfully/session.rb', line 135

def uri_to(path)
  Addressable::URI.join(uri.to_s, path.to_s)
end