Class: RHC::Rest::Base

Inherits:
Object show all
Extended by:
AttributesClass
Includes:
Attributes
Defined in:
lib/rhc/rest/base.rb

Instance Method Summary collapse

Methods included from AttributesClass

define_attr, model_name

Methods included from Attributes

#attribute, #attributes, #attributes=, #clear_attribute

Constructor Details

#initialize(attrs = nil, client = nil) ⇒ Base

Returns a new instance of Base.



11
12
13
14
15
# File 'lib/rhc/rest/base.rb', line 11

def initialize(attrs=nil, client=nil)
  @attributes = (attrs || {}).stringify_keys!
  @attributes['messages'] ||= []
  @client = client
end

Instance Method Details

#add_message(msg) ⇒ Object



17
18
19
# File 'lib/rhc/rest/base.rb', line 17

def add_message(msg)
  messages << msg
end

#has_param?(sym, name) ⇒ Boolean

Returns:

  • (Boolean)


48
49
50
51
52
# File 'lib/rhc/rest/base.rb', line 48

def has_param?(sym, name)
  if l = link(sym)
    (l['required_params'] || []).any?{ |p| p['name'] == name} or (l['optional_params'] || []).any?{ |p| p['name'] == name}
  end
end


54
55
56
57
58
59
60
61
# File 'lib/rhc/rest/base.rb', line 54

def link_href(sym, params=nil, resource=nil, &block)
  if (l = link(sym)) && (h = l['href'])
    h = h.gsub(/:\w+/){ |s| params[s].nil? ? s : CGI.escape(params[s]) } if params
    h = "#{h}/#{resource}" if resource
    return h
  end
  yield if block_given?
end


40
41
42
# File 'lib/rhc/rest/base.rb', line 40

def links
  attributes['links'] || {}
end

#rest_method(link_name, payload = {}, options = {}) ⇒ Object



21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
# File 'lib/rhc/rest/base.rb', line 21

def rest_method(link_name, payload={}, options={})
  link = link(link_name)
  raise "No link defined for #{link_name}" unless link
  url = link['href']
  url = url.gsub(/:\w+/) { |s| CGI.escape(options[:params][s]) || s } if options[:params]
  method = options[:method] || link['method']

  result = client.request(options.merge({
    :url => url,
    :method => method,
    :payload => payload,
  }))
  if result.is_a?(Hash) && (result['messages'] || result['errors'])
    attributes['messages'] = Array(result['messages'])
    result = self
  end
  result
end

#supports?(sym) ⇒ Boolean

Returns:

  • (Boolean)


44
45
46
# File 'lib/rhc/rest/base.rb', line 44

def supports?(sym)
  !!link(sym)
end