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:



44
45
46
47
48
49
50
51
52
53
54
# File 'lib/restfully/session.rb', line 44

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

  setup

  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.



134
135
136
137
138
139
140
# File 'lib/restfully/session.rb', line 134

def default_headers
  @default_headers ||= {
    'Accept' => '*/*',
    'Accept-Encoding' => 'gzip, deflate',
    'User-Agent' => "Restfully/#{Restfully::VERSION}" 
  }
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.



118
119
120
121
122
123
124
125
126
# File 'lib/restfully/session.rb', line 118

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



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

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

#disable(rack, *args) ⇒ Object

Disable a RestClient Rack component.



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

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

#enable(rack, *args) ⇒ Object

Enable a RestClient Rack component.



100
101
102
103
# File 'lib/restfully/session.rb', line 100

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



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

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

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

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



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

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

#loggerObject



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

def logger
  @config.logger
end

#middlewareObject

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



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

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



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

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

#process(response, request) ⇒ Object

Process a Restfully::HTTP::Response.



181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
# File 'lib/restfully/session.rb', line 181

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 "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



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

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

#rootObject

Returns the root Restfully::Resource.



143
144
145
# File 'lib/restfully/session.rb', line 143

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.



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

def sandbox
  Sandbox.new(self)
end

#setupObject



56
57
58
59
60
61
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
# File 'lib/restfully/session.rb', line 56

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



129
130
131
# File 'lib/restfully/session.rb', line 129

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