Class: Antaeus::Resource

Inherits:
Object
  • Object
show all
Includes:
Comparable
Defined in:
lib/antaeus-sdk/resource.rb

Overview

A generic API resource

Instance Attribute Summary collapse

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(options = {}) ⇒ Resource

Returns a new instance of Resource.



174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
# File 'lib/antaeus-sdk/resource.rb', line 174

def initialize(options = {})
  raise Exceptions::InvalidOptions unless options.is_a?(Hash)
  raise Exceptions::MissingAPIClient unless options[:client]
  raise Exceptions::InvalidAPIClient unless options[:client].is_a?(APIClient)

  if options[:entity]
    raise Exceptions::MissingEntity unless options[:entity]
    raise Exceptions::InvalidEntity unless options[:entity].is_a?(Hash)
    @entity = options[:entity]
  else
    @entity  = {}
  end
  # Allows lazy-loading if we're told this is a lazy instance
  #  This means only the minimal attributes were fetched.
  #  This shouldn't be set by end-users.
  @lazy    = options.key?(:lazy) ? options[:lazy] : false
  # This allows local, user-created instances to be differentiated from fetched
  # instances from the backend API. This shouldn't be set by end-users.
  @tainted = options.key?(:tainted) ? options[:tainted] : true
  # This is the API Client used to get data for this resource
  @client  = options[:client]
  @errors  = {}

  if immutable? && @tainted
    raise Exceptions::ImmutableInstance
  end

  # The 'id' field should not be set manually
  if @entity.key?('id')
    raise Exceptions::NewInstanceWithID unless !@tainted
  end

  self.class.class_eval do
    gen_property_methods
  end
end

Instance Attribute Details

#clientObject

Returns the value of attribute client.



4
5
6
# File 'lib/antaeus-sdk/resource.rb', line 4

def client
  @client
end

#errorsObject (readonly)

Returns the value of attribute errors.



5
6
7
# File 'lib/antaeus-sdk/resource.rb', line 5

def errors
  @errors
end

Class Method Details

.all(options = {}) ⇒ Object



98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
# File 'lib/antaeus-sdk/resource.rb', line 98

def self.all(options = {})
  validate_options(options)
  options[:lazy] = true unless options.key?(:lazy)

  # TODO: add validation checks for the required pieces
  fail(Exceptions::MissingPath) unless path_for(:all)

  root = to_underscore(self.name.split('::').last.en.plural)
  this_path = options[:lazy] ? path_for(:all) : "#{path_for(:all)}?lazy=false"

  ResourceCollection.new(
    options[:client].get(this_path)[root].collect do |record|
      self.new(
        entity: record,
        lazy: (options[:lazy] ? true : false),
        tainted: false,
        client: options[:client]
      )
    end,
    type: self,
    client: options[:client]
  )
end

.delayed_property(options = {}, &block) ⇒ Object

Delayed properties are evaluated when an instance is created WARNING: Sanity checking of the end-result isn’t possible. Use with care



14
15
16
17
18
# File 'lib/antaeus-sdk/resource.rb', line 14

def self.delayed_property(options = {}, &block)
  @properties ||= {}

  @properties[block] = options
end

.gen_property_methodsObject



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
# File 'lib/antaeus-sdk/resource.rb', line 61

def self.gen_property_methods
  properties.each do |prop, opts|
    if prop.is_a?(Proc)
      prop = prop.call.to_s.to_sym
    end

    # Getter methods
    define_method(prop) do
      if @lazy && !@entity.key?(prop.to_s)
        reload
      end
      if opts[:type] && opts[:type] == :time
        if @entity[prop.to_s] && !@entity[prop.to_s].to_s.empty?
         Time.parse(@entity[prop.to_s].to_s)
        else
         nil
       end
      else
        @entity[prop.to_s]
      end
    end

    # Setter methods (don't make one for obviously read-only properties)
    unless prop.match /\?$/ || opts[:read_only]
      define_method("#{prop}=".to_sym) do |value|
        raise Exceptions::ImmutableModification if immutable?
        if opts[:type] == :time
          @entity[prop.to_s] = Time.parse(value.to_s).utc
        else
          @entity[prop.to_s] = value
        end
        @tainted = true
      end
    end
  end
end

.get(id, options = {}) ⇒ Object



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

def self.get(id, options = {})
  validate_options(options)
  fail(Exceptions::MissingPath) unless path_for(:all)

  root = to_underscore(self.name.split('::').last)
  self.new(
    entity: options[:client].get("#{path_for(:all)}/#{id}")[root],
    lazy: false,
    tainted: false,
    client: options[:client]
  )
end

.humanObject

ActiveRecord ActiveModel::Name compatibility method



157
158
159
# File 'lib/antaeus-sdk/resource.rb', line 157

def self.human
  humanize(i18n_key)
end

.i18n_keyObject

ActiveRecord ActiveModel::Name compatibility method



162
163
164
# File 'lib/antaeus-sdk/resource.rb', line 162

def self.i18n_key
  to_underscore(self.name.split('::').last)
end

.immutable(status) ⇒ Object

Can this type of resource be changed client-side?



21
22
23
24
25
26
# File 'lib/antaeus-sdk/resource.rb', line 21

def self.immutable(status)
  unless status.is_a?(TrueClass) || status.is_a?(FalseClass)
    raise Exceptions::InvalidInput
  end
  @immutable = status
end

.immutable?Boolean

Check if a resource class is immutable

Returns:

  • (Boolean)


29
30
31
# File 'lib/antaeus-sdk/resource.rb', line 29

def self.immutable?
  @immutable ||= false
end

.param_keyObject

ActiveRecord ActiveModel::Name compatibility method



221
222
223
# File 'lib/antaeus-sdk/resource.rb', line 221

def self.param_key
  singular_route_key.to_sym
end

.path(kind, uri) ⇒ Object



48
49
50
51
# File 'lib/antaeus-sdk/resource.rb', line 48

def self.path(kind, uri)
  @paths ||= {}
  @paths[kind.to_sym] = uri
end

.path_for(kind) ⇒ Object



57
58
59
# File 'lib/antaeus-sdk/resource.rb', line 57

def self.path_for(kind)
  paths[kind.to_sym]
end

.pathsObject



53
54
55
# File 'lib/antaeus-sdk/resource.rb', line 53

def self.paths
  @paths ||= {}
end

.propertiesObject



8
9
10
# File 'lib/antaeus-sdk/resource.rb', line 8

def self.properties
  @properties ||= {}
end

.property(name, options = {}) ⇒ Object

Define a property for a model TODO: add more validations on options and names

Raises:

  • (Exception::InvalidProperty)


35
36
37
38
39
40
41
42
43
44
45
46
# File 'lib/antaeus-sdk/resource.rb', line 35

def self.property(name, options = {})
  @properties ||= {}

  invalid_prop_names = [
    :>, :<, :'=', :class, :def,
    :%, :'!', :/, :'.', :'?', :*, :'{}',
    :'[]'
  ]
  
  raise(Exception::InvalidProperty) if invalid_prop_names.include?(name.to_sym)
  @properties[name.to_sym] = options
end

.route_keyObject

ActiveRecord ActiveModel::Name compatibility method



253
254
255
# File 'lib/antaeus-sdk/resource.rb', line 253

def self.route_key
  singular_route_key.en.plural
end

.search(query, options = {}) ⇒ Object



275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
# File 'lib/antaeus-sdk/resource.rb', line 275

def self.search(query, options = {})
  validate_options(options)
  is_lazy = options.key?(:lazy) ? options[:lazy] : false
  request_uri = "#{path_for(:all)}/search?q=#{query}"
  request_uri << '&lazy=false' if !is_lazy
  root = to_underscore(self.name.split('::').last.en.plural)

  ResourceCollection.new(
    options[:client].get(request_uri)[root].collect do |record|
      self.new(
        entity: record,
        lazy: is_lazy,
        tainted: false,
        client: options[:client]
      )
    end,
    type: self,
    client: options[:client]
  )
end

.singular_route_keyObject

ActiveRecord ActiveModel::Name compatibility method



258
259
260
# File 'lib/antaeus-sdk/resource.rb', line 258

def self.singular_route_key
  to_underscore(self.name.split('::').last)
end

.where(attribute, value, options = {}) ⇒ Object



135
136
137
138
139
# File 'lib/antaeus-sdk/resource.rb', line 135

def self.where(attribute, value, options = {})
  validate_options(options)
  options[:comparison] ||= '=='
  all(lazy: (options[:lazy] ? true : false), client: options[:client]).where(attribute, value, comparison: options[:comparison])
end

Instance Method Details

#<=>(other) ⇒ Object



315
316
317
318
319
320
321
322
323
324
325
# File 'lib/antaeus-sdk/resource.rb', line 315

def <=>(other)
  if id < other.id
    -1
  elsif id > other.id
    1
  elsif id == other.id
    0
  else
    raise Exceptions::InvalidInput
  end
end

#destroyObject



141
142
143
144
145
146
147
148
149
150
# File 'lib/antaeus-sdk/resource.rb', line 141

def destroy
  fail Exceptions::ImmutableInstance if immutable?
  unless new?
    @client.delete("#{path_for(:all)}/#{id}")
    @lazy = false
    @tainted = true
    @entity.delete('id')
  end
  true
end

#fresh?Boolean

Returns:

  • (Boolean)


152
153
154
# File 'lib/antaeus-sdk/resource.rb', line 152

def fresh?
  !tainted?
end

#idObject



166
167
168
# File 'lib/antaeus-sdk/resource.rb', line 166

def id
  @entity['id']
end

#immutable?Boolean

Returns:

  • (Boolean)


170
171
172
# File 'lib/antaeus-sdk/resource.rb', line 170

def immutable?
  self.class.immutable?
end

#model_nameObject

ActiveRecord ActiveModel::Name compatibility method



212
213
214
# File 'lib/antaeus-sdk/resource.rb', line 212

def model_name
  self.class
end

#new?Boolean

Returns:

  • (Boolean)


216
217
218
# File 'lib/antaeus-sdk/resource.rb', line 216

def new?
  !@entity.key?('id')
end

#path_for(kind) ⇒ Object



229
230
231
# File 'lib/antaeus-sdk/resource.rb', line 229

def path_for(kind)
  self.class.path_for(kind)
end

#pathsObject



225
226
227
# File 'lib/antaeus-sdk/resource.rb', line 225

def paths
  self.class.paths
end

#persisted?Boolean

ActiveRecord ActiveModel::Model compatibility method

Returns:

  • (Boolean)


234
235
236
# File 'lib/antaeus-sdk/resource.rb', line 234

def persisted?
  !new?
end

#reloadObject



238
239
240
241
242
243
244
245
246
247
248
249
250
# File 'lib/antaeus-sdk/resource.rb', line 238

def reload
  root = to_underscore(self.class.name.split('::').last)

  if new?
    # Can't reload a new resource
    false
  else
    @entity  = @client.get("#{path_for(:all)}/#{id}")[root]
    @lazy    = false
    @tainted = false
    true
  end
end

#saveObject



262
263
264
265
266
267
268
269
270
271
272
273
# File 'lib/antaeus-sdk/resource.rb', line 262

def save
  root = to_underscore(self.class.name.split('::').last)

  if new?
    @entity  = @client.post("#{path_for(:all)}", @entity)[root]
    @lazy    = false
  else
    @client.put("#{path_for(:all)}/#{id}", @entity)
  end
  @tainted = false
  true
end

#tainted?Boolean

Returns:

  • (Boolean)


296
297
298
# File 'lib/antaeus-sdk/resource.rb', line 296

def tainted?
  @tainted ? true : false
end

#to_keyObject

ActiveRecord ActiveModel::Conversion compatibility method



301
302
303
# File 'lib/antaeus-sdk/resource.rb', line 301

def to_key
  new? ? [] : [id]
end

#to_modelObject

ActiveRecord ActiveModel::Conversion compatibility method



306
307
308
# File 'lib/antaeus-sdk/resource.rb', line 306

def to_model
  self
end

#to_paramObject

ActiveRecord ActiveModel::Conversion compatibility method



311
312
313
# File 'lib/antaeus-sdk/resource.rb', line 311

def to_param
  new? ? nil : id.to_s
end

#update(params) ⇒ Object

ActiveRecord ActiveModel compatibility method



328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
# File 'lib/antaeus-sdk/resource.rb', line 328

def update(params)
  new_params = {}
  # need to convert multi-part datetime params
  params.each do |key, value|
    if key.match /([^(]+)\(1i/
      actual_key = key.match(/([^(]+)\(/)[1]
      new_params[actual_key] = DateTime.new(
        params["#{actual_key}(1i)"].to_i,
        params["#{actual_key}(2i)"].to_i,
        params["#{actual_key}(3i)"].to_i,
        params["#{actual_key}(4i)"].to_i,
        params["#{actual_key}(5i)"].to_i
      )
    elsif key.match /([^(]+)\(/
      # skip this... already got it
    else
      new_params[key] = value
    end
  end
      
  new_params.each do |key, value|
    raise Exceptions::InvalidProperty unless self.respond_to?("#{key}=".to_sym)
    send("#{key}=".to_sym, value)
  end
  save
end