Class: MoxiworksPlatform::Resource

Inherits:
Object
  • Object
show all
Defined in:
lib/moxiworks_platform/resource.rb

Overview

provides underlying logic for connecting to Moxi Works Platform over HTTPS

Instance Attribute Summary collapse

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(hash = {}) ⇒ Resource

maps Hash values to Instance variables for mapping JSON object values to our Class attributes



164
165
166
# File 'lib/moxiworks_platform/resource.rb', line 164

def initialize(hash={})
  self.init_attrs_from_hash(hash)
end

Dynamic Method Handling

This class handles dynamic methods through the method_missing method

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



193
194
195
196
197
198
199
200
# File 'lib/moxiworks_platform/resource.rb', line 193

def method_missing(meth, *args, &block)
  name = meth.to_sym
  if numeric_attrs.include? name
    return numeric_value_for(name, type: :integer) if int_attrs.include? name
    return numeric_value_for(name, type: :float) if float_attrs.include? name
  end
  super(meth, *args, &block)
end

Instance Attribute Details

#headersObject

Returns the value of attribute headers.



9
10
11
# File 'lib/moxiworks_platform/resource.rb', line 9

def headers
  @headers
end

Class Method Details

.accept_headerString

formatted Accept header content

Returns:

  • (String)

    Accept header content



59
60
61
# File 'lib/moxiworks_platform/resource.rb', line 59

def self.accept_header
  'application/vnd.moxi-platform+json;version=1'
end

.attr_accessor(*vars) ⇒ Object

keep a list of attr_accessors defined in this class

used to convert Resource child object into parameters required for saving in Moxi Works Platform



18
19
20
21
22
# File 'lib/moxiworks_platform/resource.rb', line 18

def self.attr_accessor(*vars)
  @attributes ||= []
  @attributes.concat vars
  super(*vars)
end

.attributesArray

all available accessors defined in this class

Returns:

  • (Array)
    String

    all defined accessors of this class



27
28
29
# File 'lib/moxiworks_platform/resource.rb', line 27

def self.attributes
  @attributes
end

.auth_headerString

formatted Authorization header content

Returns:

  • (String)

    Authorization header content

Raises:



47
48
49
50
51
52
53
54
# File 'lib/moxiworks_platform/resource.rb', line 47

def self.auth_header
  raise MoxiworksPlatform::Exception::AuthorizationError,
        'MoxiworksPlatform::Credentials must be set before using' unless
      MoxiworksPlatform::Credentials.set?
  identifier = MoxiworksPlatform::Credentials.platform_identifier
  secret = MoxiworksPlatform::Credentials.platform_secret
  'Basic ' + Base64.encode64("#{identifier}:#{secret}").gsub(/\n/, '')
end

.check_for_error_in_response(response) ⇒ Object



74
75
76
77
78
79
80
81
82
83
84
85
86
87
# File 'lib/moxiworks_platform/resource.rb', line 74

def self.check_for_error_in_response(response)
  begin
    json = JSON.parse(response)
    MoxiworksPlatform::Session.instance.cookie = response.headers[:set_cookie].first rescue nil
    return if json.is_a?(Array)
    rescue => e
    raise MoxiworksPlatform::Exception::RemoteRequestFailure, "unable to parse remote response #{e}\n response:\n  #{response}"
  end
  message = "unable to perform remote action on Moxi Works platform\n"
  message << json['messages'].join(',') unless json['messages'].nil?

  raise MoxiworksPlatform::Exception::RemoteRequestFailure, message  if
      not json['status'].nil? and (%w(error fail).include?(json['status']))
end

.content_type_headerString

formatted Content-Type header

Returns:

  • (String)

    Content-Type header content



66
67
68
# File 'lib/moxiworks_platform/resource.rb', line 66

def self.content_type_header
  'application/x-www-form-urlencoded'
end

.headersHash

HTTP headers required to connect to Moxi Works Platform

Returns:

  • (Hash)

    formatted headers suitable for a RestClient connection



34
35
36
37
38
39
40
41
42
# File 'lib/moxiworks_platform/resource.rb', line 34

def self.headers
  {
      Authorization: auth_header,
      Accept: accept_header,
      'Content-Type' =>  content_type_header,
      Cookie: Session.instance.cookie,
      'X-Moxi-Library-User-Agent' => user_agent_header
  }
end

.send_request(method, opts = {}, url = nil) ⇒ Object



89
90
91
92
93
94
95
96
97
98
99
100
101
# File 'lib/moxiworks_platform/resource.rb', line 89

def self.send_request(method, opts={}, url=nil)
  RestClient::Request.execute(method: method,
                              url: url,
                              payload: opts, headers: self.headers) do |response|
    puts response if MoxiworksPlatform::Config.debug
    self.check_for_error_in_response(response)
    json = JSON.parse(response)
    return false if not json['status'].nil? and json['status'] =='fail'
    r = self.new(json) unless json.nil? or json.empty?
    r.headers = response.headers unless r.nil?
    r
  end
end

.underscore(attr) ⇒ Object



152
153
154
155
156
157
158
# File 'lib/moxiworks_platform/resource.rb', line 152

def self.underscore(attr)
  attr.gsub(/::/, '/').
      gsub(/([A-Z]+)([A-Z][a-z])/,'\1_\2').
      gsub(/([a-z\d])([A-Z])/,'\1_\2').
      tr("-", "_").
      downcase
end

.underscore_array(array) ⇒ Object



135
136
137
138
139
140
141
# File 'lib/moxiworks_platform/resource.rb', line 135

def self.underscore_array(array)
  new_array = []
  array.each do |member|
    new_array << self.underscore_attribute_names(member)
  end
  new_array
end

.underscore_attribute_names(thing) ⇒ Object



123
124
125
126
127
128
129
130
131
132
133
# File 'lib/moxiworks_platform/resource.rb', line 123

def self.underscore_attribute_names(thing)
  case thing
    when Array
      new_thing = self.underscore_array(thing)
    when Hash
      new_thing = self.underscore_hash(thing)
    else
      new_thing = thing
  end
  new_thing
end

.underscore_hash(hash) ⇒ Object



143
144
145
146
147
148
149
150
# File 'lib/moxiworks_platform/resource.rb', line 143

def self.underscore_hash(hash)
  hash.keys.each do |key|
    hash[key] = self.underscore_attribute_names hash[key]
    underscored = Resource.underscore(key)
    hash[underscored] = hash.delete(key)
  end
  hash
end

.user_agent_headerObject



70
71
72
# File 'lib/moxiworks_platform/resource.rb', line 70

def self.user_agent_header
  'moxiworks_platform ruby client'
end

Instance Method Details

#attributesArray

all available accessors defined in this class

Returns:

  • (Array)
    String

    all defined accessors of this class



171
172
173
# File 'lib/moxiworks_platform/resource.rb', line 171

def attributes
  self.class.attributes + numeric_attrs
end

#float_attrsObject

used by method_missing to ensure that a number is the type we expect it to be this should be overridden if we have any float values we want to return as floats



177
178
179
# File 'lib/moxiworks_platform/resource.rb', line 177

def float_attrs
  []
end

#init_attrs_from_hash(hash = {}) ⇒ Object



187
188
189
190
191
# File 'lib/moxiworks_platform/resource.rb', line 187

def init_attrs_from_hash(hash={})
  hash.each do |key,val|
    instance_variable_set("@#{key}", val)
  end
end

#int_attrsObject

used by method_missing to ensure that a number is the type we expect it to be this should be overridden if we have any int values we want to return as ints



183
184
185
# File 'lib/moxiworks_platform/resource.rb', line 183

def int_attrs
  []
end

#numeric_attrsObject

used by method_missing to ensure that a number is the type we expect it to be



203
204
205
# File 'lib/moxiworks_platform/resource.rb', line 203

def numeric_attrs
  int_attrs + float_attrs
end

#numeric_value_for(attr_name, opts = {}) ⇒ Object



103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
# File 'lib/moxiworks_platform/resource.rb', line 103

def numeric_value_for(attr_name, opts={})
  val = self.instance_variable_get("@#{attr_name}")
  return val.to_i if val.is_a? Numeric and opts[:type] == :integer
  return val if val.is_a? Numeric
  return nil if val.nil? or val.empty?
  val.gsub!(/[^[:digit:]|\.]/, '') if val.is_a? String
  case opts[:type]
    when :integer
      instance_variable_set("@#{attr_name}", (val.nil? or val.empty?) ? nil : val.to_i)
    when :float
      instance_variable_set("@#{attr_name}", (val.nil? or val.empty?) ? nil : val.to_f)
    else
      instance_variable_set("@#{attr_name}", nil)
  end
  self.instance_variable_get("@#{attr_name}")
rescue => e
  puts "problem with auto conversion: #{e.message} #{e.backtrace}"
  nil
end

#to_hashHash

convert this class into a Hash structure where attributes are Hash key names and attribute values are Hash values

Returns:

  • (Hash)

    with keys mapped to class attribute names



210
211
212
213
214
# File 'lib/moxiworks_platform/resource.rb', line 210

def to_hash
  hash = {}
  self.attributes.each {|attr| hash[attr.to_sym] = self.send(attr)}
  hash
end