Class: RESTHome

Inherits:
Object
  • Object
show all
Includes:
HTTParty
Defined in:
lib/resthome.rb,
lib/active_support/instrumentation.rb

Defined Under Namespace

Classes: Error, InvalidResponse, LogSubscriber, MethodMissing

Instance Attribute Summary collapse

Class Method Summary collapse

Instance Method Summary collapse

Dynamic Method Handling

This class handles dynamic methods through the method_missing method

#method_missing(method, *args, &block) ⇒ Object

:nodoc:



271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
# File 'lib/resthome.rb', line 271

def method_missing(method, *args, &block) #:nodoc:
  if method.to_s =~ /^find_(.*?)_by_(.*)$/
    find_method = "find_#{$1}"
    find_args = $2.split '_and_'
    raise MethodMissing.new "Missing method #{find_method}" unless self.class.method_defined?(find_method)
    start = (self.method(find_method).arity + 1).abs
    options = args[-1].is_a?(Hash) ? args[-1] : {}
    options[:query] ||= {}
    find_args.each_with_index do |find_arg, idx|
      options[:query][find_arg] = args[start+idx]
    end

    if start > 0
      send_args = args[0..(start-1)]
      send_args << options
      return self.send(find_method, *send_args, &block)
    else
      return self.send(find_method, options, &block)
    end
  else
    super
  end
end

Instance Attribute Details

#base_uriObject

Returns the value of attribute base_uri.



12
13
14
# File 'lib/resthome.rb', line 12

def base_uri
  @base_uri
end

#basic_authObject

Returns the value of attribute basic_auth.



12
13
14
# File 'lib/resthome.rb', line 12

def basic_auth
  @basic_auth
end

#cookiesObject

Returns the value of attribute cookies.



12
13
14
# File 'lib/resthome.rb', line 12

def cookies
  @cookies
end

#request_methodObject (readonly)

Returns the value of attribute request_method.



13
14
15
# File 'lib/resthome.rb', line 13

def request_method
  @request_method
end

#request_optionsObject (readonly)

Returns the value of attribute request_options.



13
14
15
# File 'lib/resthome.rb', line 13

def request_options
  @request_options
end

#request_urlObject (readonly)

Returns the value of attribute request_url.



13
14
15
# File 'lib/resthome.rb', line 13

def request_url
  @request_url
end

#responseObject (readonly)

Returns the value of attribute response.



13
14
15
# File 'lib/resthome.rb', line 13

def response
  @response
end

Class Method Details

.namespace(path_prefix) ⇒ Object



179
180
181
182
183
184
# File 'lib/resthome.rb', line 179

def self.namespace(path_prefix)
  @path_prefix ||= []
  @path_prefix.push path_prefix
  yield
  @path_prefix.pop
end

.register_route_block(route, proc) ⇒ Object

:nodoc:



319
320
321
322
323
324
325
326
327
# File 'lib/resthome.rb', line 319

def self.register_route_block(route, proc) #:nodoc:
  blocks = self.route_blocks
  blocks[route.to_s] = proc

  sing = class << self; self; end
  sing.send :define_method, :route_blocks do 
    blocks
  end 
end

.rest(resource_name, collection_name, base_path, options = {}) ⇒ Object

Creates routes for a RESTful API

resource_name is the name of the items returned by the API, collection_name is the plural name of the items, base_path is the path to the collection

Sets up 5 most common RESTful routes

Example

/customers.json GET list of customers, POST to create a customer
/customers/1.json GET a customers, PUT to edit a customer, DELETE to delete a customer
JSON response returns {'customer': {'id':1, 'name':'Joe', ...}}

Setup the RESTful routes

rest :customer, :customers, '/customers.json'
# same as
route :customers, '/customers.json', :resource => :customer
route :create_customer, '/customers.json', :resource => :customer
route :customer, '/customers/:customer_id.json', :resource => :customer
route :edit_customer, '/customers/:customer_id.json', :resource => :customer
route :delete_customer, '/customers/:customer_id.json', :resource => :customer

Following methods are created

customers # return an array of customers
create_customer :name => 'Smith' # returns {'id' => 2, 'name' => 'Smith'}
customer 1 # return data for customer 1
edit_customer 1, :name => 'Joesph'
delete_customer 1


214
215
216
217
218
219
220
221
# File 'lib/resthome.rb', line 214

def self.rest(resource_name, collection_name, base_path, options={})
  options[:resource] ||= resource_name
  self.route collection_name, base_path, options
  self.route resource_name, base_path.sub(/(\.[a-zA-Z0-9]+)$/, "/:#{resource_name}_id\\1"), options
  self.route "edit_#{resource_name}", base_path.sub(/(\.[a-zA-Z0-9]+)$/, "/:#{resource_name}_id\\1"), options
  self.route "create_#{resource_name}", base_path, options
  self.route "delete_#{resource_name}", base_path.sub(/(\.[a-zA-Z0-9]+)$/, "/:#{resource_name}_id\\1"), options
end

.route(name, path, options = {}, &block) ⇒ Object

Defines a web service route

Arguments

name of the method to create name has special meaning.

  • If starts with create or add the method will be set to POST.

  • If starts with edit or update the method will be set to PUT.

  • If starts with delete the method will be set to DELETE.

  • Else by default the method is GET.

path is the path to the web service

Options

:method

The request method get/post/put/delete. Default is get.

:expected_status

Expected status code of the response, will raise InvalidResponse. Can be an array of codes.

:return

The method to call, the class to create or a Proc to call before method returns.

:resource

The name of the element to return from the response.

:no_body

Removes the body argument from a post/put route

:query

Default set of query arguments

:body

Default set of body arguments



43
44
45
46
47
48
49
50
51
52
53
54
55
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
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
# File 'lib/resthome.rb', line 43

def self.route(name, path, options={}, &block)
  args = path.scan /:[a-z_]+/
  path = "#{@path_prefix.join if @path_prefix}#{path}"
  function_args = []
  args.each_with_index{ |arg| function_args << "arg#{function_args.size}" }

  body_args = get_function_args options, :body
  body_args.each { |arg| function_args << "arg#{function_args.size}" }

  query_args = get_function_args options, :query
  query_args.each { |arg| function_args << "arg#{function_args.size}" }

  method = options[:method]
  if method.nil?
    if name.to_s =~ /^(create|add|edit|update|delete)_/
      case $1
      when 'create'
        method = 'post'
      when 'add'
        method = 'post'
      when 'edit'
        method = 'put'
      when 'update'
        method = 'put'
      when 'delete'
        method = 'delete'
      end
    else
      method = 'get'
    end
  end
  method = method.to_s

  expected_status = options[:expected_status]
  if expected_status.nil?
    case method
    when 'post'
      expected_status ||= [200, 201]
    when 'delete'
      expected_status ||= [200, 204]
    else
      expected_status ||= 200
    end
  end

  function_args << 'body' if (method == 'post' || method == 'put') && options[:no_body].nil?
  function_args << 'options={}, &block'

  method_src = "  def \#{name}(\#{function_args.join(',')})\n    path = \"\#{path}\"\n  METHOD\n\n  args.each_with_index do |arg, idx|\n    method_src << \"path.sub! '\#{arg}', URI.escape(\#{function_args[idx]}.to_s)\\n\"\n  end\n\n  if options[:no_body]\n    if options[:body]\n      method_src << \"options[:body] = \#{options[:body].inspect}.merge(options[:body] || {})\\n\"\n    elsif body_args.size > 0\n      method_src << \"options[:body] ||= {}\\n\"\n    end\n  else\n    if method == 'post' || method == 'put'\n      if options[:resource]\n        method_src << \"options[:body] = {'\#{options[:resource].to_s}' => body}\\n\"\n      elsif options[:body]\n        method_src << \"options[:body] = \#{options[:body].inspect}.merge(body || {})\\n\"\n      else\n        method_src << \"options[:body] = body\\n\"\n      end\n    end\n  end\n\n  if options[:query]\n    method_src << \"options[:query] = \#{options[:query].inspect}.merge(options[:query] || {})\\n\"\n  elsif query_args.size > 0\n    method_src << \"options[:query] ||= {}\\n\"\n  end\n\n  body_args.each_with_index do |arg, idx|\n    idx += args.size\n    method_src << \"options[:body]['\#{arg}'] = \#{function_args[idx]}\\n\"\n  end\n\n  query_args.each_with_index do |arg, idx|\n    idx += body_args.size + args.size\n    method_src << \"options[:query]['\#{arg}'] = \#{function_args[idx]}\\n\"\n  end\n\n  method_src << \"request :\#{method}, path, options\\n\"\n\n  if expected_status\n    if expected_status.is_a?(Array)\n      method_src << 'raise InvalidResponse.new \"Invalid response code \#{response.code}\" if ! [' + expected_status.join(',') + \"].include?(response.code)\\n\"\n    else\n      method_src << 'raise InvalidResponse.new \"Invalid response code \#{response.code}\" if response.code != ' + expected_status.to_s + \"\\n\"\n    end\n  end\n\n  return_method = 'nil'\n  if options[:return].nil? || options[:return].is_a?(Proc)\n    block ||= options[:return]\n    if block\n      register_route_block name, block\n      return_method = \"self.class.route_blocks['\#{name}']\"\n    end\n  elsif options[:return].is_a?(Class)\n    return_method = options[:return].to_s\n  else\n    return_method = \":\#{options[:return]}\"\n  end\n\n  resource = options[:resource] ? \"'\#{options[:resource]}'\" : 'nil'\n\n  method_src << \"parse_response!\\n\"\n\n  method_src << \"_handle_response response, :resource => \#{resource}, :return => \#{return_method}, &block\\n\"\n\n  method_src << \"end\\n\"\n\n  if options[:instance]\n    options[:instance].instance_eval method_src, __FILE__, __LINE__\n  elsif options[:class]\n    options[:class].class_eval method_src, __FILE__, __LINE__\n  else\n    self.class_eval method_src, __FILE__, __LINE__\n  end\nend\n"

.route_blocksObject

:nodoc:



315
316
317
# File 'lib/resthome.rb', line 315

def self.route_blocks #:nodoc:
  {}
end

Instance Method Details

#build_options!(options) ⇒ Object

Adds the basic_auth and cookie options This method should be overwritten as needed.



230
231
232
233
234
235
236
# File 'lib/resthome.rb', line 230

def build_options!(options)
  options[:basic_auth] = self.basic_auth if self.basic_auth
  if @cookies
    options[:headers] ||= {}
    options[:headers]['cookie'] = @cookies.to_a.collect{|c| "#{c[0]}=#{c[1]}"}.join('; ') + ';'
  end
end

#build_url(path) ⇒ Object

Creates the url



224
225
226
# File 'lib/resthome.rb', line 224

def build_url(path)
  "#{self.base_uri || self.class.base_uri}#{path}"
end

#parse_response!Object

Called after every valid request. Useful for parsing response headers. This method should be overwritten as needed.



311
312
313
# File 'lib/resthome.rb', line 311

def parse_response!
  save_cookies!
end

#request(method, path, options) ⇒ Object

Makes the request using HTTParty. Saves the method, path and options used.



239
240
241
242
243
244
245
246
247
# File 'lib/resthome.rb', line 239

def request(method, path, options)
  build_options! options
  url = build_url path
  @request_method = method
  @request_url = url
  @request_options = options

  @response = self.class.send(method, url, options)
end

#request_with_instrumentation(method, path, options) ⇒ Object



2
3
4
5
6
# File 'lib/active_support/instrumentation.rb', line 2

def request_with_instrumentation(method, path, options)
  ActiveSupport::Notifications.instrument("request.resthome", :client => self.class.name, method: method, path: path) do
    request_without_instrumentation(method, path, options)
  end
end

#route(name, path, options = {}) ⇒ Object

Adds a route to the current object



175
176
177
# File 'lib/resthome.rb', line 175

def route(name, path, options={})
  self.class.route name, path, options.merge(:instance => self)
end

#save(name, body, options = {}) ⇒ Object

Will either call edit_<name> or add_<name> based on wether or not the body exists.



250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
# File 'lib/resthome.rb', line 250

def save(name, body, options={})
  id = body[:id] || body['id']
  if id
    if self.class.method_defined?("edit_#{name}")
      self.send("edit_#{name}", id, body, options)
    elsif self.class.method_defined?("update_#{name}")
      self.send("update_#{name}", id, body, options)
    else
      raise MethodMissing.new "No edit/update method found for #{name}"
    end
  else
    if self.class.method_defined?("add_#{name}")
      self.send("add_#{name}", body, options)
    elsif self.class.method_defined?("create_#{name}")
      self.send("create_#{name}", body, options)
    else
      raise MethodMissing.new "No add/create method found for #{name}"
    end
  end
end

#save_cookies(data) ⇒ Object

Parse an array of Set-cookie headers



302
303
304
305
306
307
# File 'lib/resthome.rb', line 302

def save_cookies(data)
  @cookies ||= {}
  data.delete_if{ |c| c.nil? || c.empty? }.collect { |cookie| parts = cookie.split("\; "); parts[0] ? parts[0].split('=') : nil }.each do |c|
    @cookies[c[0].strip] = c[1].strip if c && c[0] && c[1]
  end
end

#save_cookies!Object

Convenience method for saving all cookies by default called from parse_response!.



296
297
298
299
# File 'lib/resthome.rb', line 296

def save_cookies!
  return unless @response.headers.to_hash['set-cookie']
  save_cookies @response.headers.to_hash['set-cookie']
end