Module: Bodhi::Resource::ClassMethods

Included in:
Bodhi::Resource
Defined in:
lib/bodhi-slam/resource.rb

Instance Method Summary collapse

Instance Method Details

#aggregate(context, pipeline) ⇒ Hash

Note:

Large aggregations can be very time and resource intensive!

Performs MongoDB aggregations using the given pipeline

Equivalent CURL command:

curl -u {username}:{password} https://{server}/{namespace}/resources/{resource}/aggregate?pipeline={pipeline}

Examples:

Resource.aggregate(context, "[{ $match: { age: { $gte: 21 }}}]")

Parameters:

Returns:

  • (Hash)

    the JSON response converted to a Ruby Hash

Raises:



238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
# File 'lib/bodhi-slam/resource.rb', line 238

def aggregate(context, pipeline)
  if context.invalid?
    raise Bodhi::ContextErrors.new(context.errors.messages), context.errors.to_a.to_s
  end

  unless pipeline.is_a? String
    raise ArgumentError.new("Expected 'pipeline' to be a String. 'pipeline' #=> #{pipeline.class}")
  end

  result = context.connection.get do |request|
    request.url "/#{context.namespace}/resources/#{name}/aggregate?pipeline=#{pipeline}"
    request.headers[context.credentials_header] = context.credentials
  end

  if result.status != 200
    raise Bodhi::ApiErrors.new(body: result.body, status: result.status), "status: #{result.status}, body: #{result.body}"
  end

  result.body
end

#build_typeBodhi::Type

Generates a new Type instance using the classes metadata

Examples:

class User
  include Bodhi::Resource

  field :first_name, type: "String", required: true, is_not_blank: true
  field :last_name, type: "String", required: true, is_not_blank: true
  field :email, type: "String", required: true, is_not_blank: true, is_email: true

  index ["last_name"]
end

User.build_type #=> #<Bodhi::Type:0x007fbff403e808 @name="User" @properties={...} @indexes=[...]>

Returns:



62
63
64
# File 'lib/bodhi-slam/resource.rb', line 62

def build_type
  Bodhi::Type.new(name: self.name, properties: self.properties, indexes: self.indexes, embedded: self.is_embedded?)
end

#count(context, query = {}) ⇒ Object

Counts all records that match the given query

Equivalent CURL command:

curl -u {username}:{password} https://{server}/{namespace}/resources/{resource}/count?where={query}

Examples:

Resource.count(context) #=> # count all records
Resource.count(context, name: "Foo") #=> # count all records with name == "Foo"

Parameters:

  • context (Bodhi::Context)
  • query (Hash) (defaults to: {})

    MongoDB query operations



89
90
91
92
93
# File 'lib/bodhi-slam/resource.rb', line 89

def count(context, query={})
  query_obj = Bodhi::Query.new(name)
  query_obj.where(query).from(context)
  query_obj.count
end

#create!(context, properties) ⇒ Bodhi::Resource

Creates a new resource with the given properties and POSTs it to the IoT Platform

Equivalent CURL command:

curl -u {username}:{password} -X POST -H "Content-Type: application/json" \
https://{server}/{namespace}/resources/{resource} \
-d '{properties}'

Parameters:

Returns:

Raises:

  • (Bodhi::ContextErrors)

    if the given Bodhi::Context is invalid

  • (Bodhi::ApiErrors)

    if the record cannot be saved Resource.create!(context, name: “Foo”, age: 125, tags: [“green”, “blue”])



129
130
131
132
133
134
135
136
137
138
139
140
141
# File 'lib/bodhi-slam/resource.rb', line 129

def create!(context, properties)
  if context.invalid?
    raise Bodhi::ContextErrors.new(context.errors.messages), context.errors.to_a.to_s
  end

  # Build a new record and set the context
  record = self.new(properties)
  record.bodhi_context = context

  # POST to the IoT Platform
  record.save!
  return record
end

#delete!(context, query = {}) ⇒ Hash

TODO:

add more query complex examples

Note:

Beware: It’s easy to delete an entire collection with this method! Use it wisely :)

Deletes all records that match the given query

Equivalent CURL command:

curl -u {username}:{password} -X DELETE https://{server}/{namespace}/resources/{resource}?where={query}

Examples:

# delete with a query
Resource.delete!(context, sys_created_at: { '$lte': 6.months.ago.iso8601 })

# delete all records
Resource.delete!(context)

Parameters:

  • context (Bodhi::Context)
  • query (Hash) (defaults to: {})

    MongoDB query operations

Returns:

  • (Hash)

    with key: count



110
111
112
113
114
# File 'lib/bodhi-slam/resource.rb', line 110

def delete!(context, query={})
  query_obj = Bodhi::Query.new(name)
  query_obj.where(query).from(context)
  query_obj.delete
end

#embedded(status) ⇒ Boolean

Sets the resources embedded status to either true/false.

Parameters:

  • status (Boolean)

Returns:

  • (Boolean)


17
# File 'lib/bodhi-slam/resource.rb', line 17

def embedded(status); @embedded = status; end

#field(name, options) ⇒ Object

Defines the given name and options as a form attribute for the class. The name is set as a property, and validations & factory generators are added based on the supplied options

Examples:

class User
  include Bodhi::Resource

  field :first_name, type: "String", required: true, is_not_blank: true
  field :last_name, type: "String", required: true, is_not_blank: true
  field :email, type: "String", required: true, is_not_blank: true, is_email: true
end

object = User.new(first_name: "John", last_name: "Smith", email: "[email protected]")
object.to_json #=> { "first_name": "John", "last_name": "Smith", "email": "[email protected]" }

Parameters:

  • name (String)
  • options (Hash)


41
42
43
44
45
# File 'lib/bodhi-slam/resource.rb', line 41

def field(name, options)
  property(name.to_sym, options)
  validates(name.to_sym, options)
  generates(name.to_sym, options)
end

#find(id, context = nil) ⇒ Bodhi::Resource

Search for a record with the given id

Equivalent CURL command:

curl -u {username}:{password} https://{server}/{namespace}/resources/{resource}/{id}

Examples:

context = Bodhi::Context.new
id = Resource.factory.create(context).sys_id
obj = Resource.find(context, id)

Parameters:

  • id (String)

    the Properties#sys_id of the record

  • context (Bodhi::Context) (defaults to: nil)

Returns:

Raises:



157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
# File 'lib/bodhi-slam/resource.rb', line 157

def find(id, context=nil)
  if context.nil?
    context = Bodhi::Context.global_context
  end

  if context.invalid?
    raise Bodhi::ContextErrors.new(context.errors.messages), context.errors.to_a.to_s
  end

  unless id.is_a? String
    raise ArgumentError.new("Expected 'id' to be a String. 'id' #=> #{id.class}")
  end

  result = context.connection.get do |request|
    request.url "/#{context.namespace}/resources/#{name}/#{id}"
    request.headers[context.credentials_header] = context.credentials
  end

  if result.status != 200
    raise Bodhi::ApiErrors.new(body: result.body, status: result.status), "status: #{result.status}, body: #{result.body}"
  end

  record = Object.const_get(name).new(result.body)
  record.bodhi_context = context
  record
end

#find_all(context = nil) ⇒ Array<Bodhi::Resource> Also known as: all

Note:

This method will return ALL records!! Don’t use on large collections! YE BE WARNED!!

Returns all records in the given context

All records returned by this method will have their Bodhi::Resource#bodhi_context attribute set to context

Examples:

Resource.find_all(context) # => [#<Resource:0x007fbff403e808>, #<Resource:0x007fbff403e808>, ...]

Parameters:

Returns:

Raises:



195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
# File 'lib/bodhi-slam/resource.rb', line 195

def find_all(context=nil)
  if context.nil?
    context = Bodhi::Context.global_context
  end

  if context.invalid?
    raise Bodhi::ContextErrors.new(context.errors.messages), context.errors.to_a.to_s
  end

  page = 1
  records = []

  begin
    result = context.connection.get do |request|
      request.url "/#{context.namespace}/resources/#{name}?paging=page:#{page}"
      request.headers[context.credentials_header] = context.credentials
    end

    if result.status != 200
      raise Bodhi::ApiErrors.new(body: result.body, status: result.status), "status: #{result.status}, body: #{result.body}"
    end

    page += 1
    records << result.body
  end until result.body.size != 100

  records.flatten.collect{ |record| Object.const_get(name).new(record.merge(bodhi_context: context)) }
end

#is_embedded?Boolean

Checks if the resource is embedded

Returns:

  • (Boolean)


22
# File 'lib/bodhi-slam/resource.rb', line 22

def is_embedded?; @embedded; end

#save_batch(context, objects) ⇒ Object

Deprecated.

This uses the old bulk upload process and will be removed in version 1.0.0 DO NOT USE!

Saves a batch of resources to the Bodhi Cloud in the given context Returns an array of JSON objects describing the results for each record in the batch

Examples:

context = Bodhi::Context.new
list = Resource.factory.build_list(10)
Resource.save_batch(context, list)


74
75
76
77
78
# File 'lib/bodhi-slam/resource.rb', line 74

def save_batch(context, objects)
  batch = Bodhi::ResourceBatch.new(name, objects)
  batch.save!(context)
  batch
end

#where(query) ⇒ Bodhi::Query<Bodhi::Resource>

Returns a Query object with the given query

Examples:

context = Bodhi::Context.new
Resource.where({conditions}).from(context).all
Resource.where({conditions}).and({more conditions}).limit(10).from(context).all

Parameters:

  • query (Hash)

    the MongoDB query operations

Returns:



267
268
269
270
271
# File 'lib/bodhi-slam/resource.rb', line 267

def where(query)
  query_obj = Bodhi::Query.new(name)
  query_obj.where(query)
  query_obj
end