Class: Supplejack::UserSet

Inherits:
Object
  • Object
show all
Extended by:
ActiveModel::Naming, Request
Includes:
ActiveModel::Conversion
Defined in:
lib/supplejack/user_set.rb

Overview

The UserSet class represents a UserSet on the Supplejack API

A UserSet instance can have many Item objects, the relationship with the Item objects is managed through the ItemRelation class which adds ActiveRecord like behaviour to the relationship.

A Item object can have the following values:

  • id

  • name

  • description

  • privacy

  • priority

  • count

  • tags

Constant Summary collapse

ATTRIBUTES =
[:id, :name, :description, :privacy, :url, :priority, :count, :tags, :tag_list, 
:featured, :records, :created_at, :updated_at, :approved, :record]
PRIVACY_STATES =
['public', 'hidden', 'private']

Instance Attribute Summary collapse

Class Method Summary collapse

Instance Method Summary collapse

Methods included from Request

delete, get, post, put

Constructor Details

#initialize(attributes = {}) ⇒ UserSet

Returns a new instance of UserSet.



37
38
39
40
41
# File 'lib/supplejack/user_set.rb', line 37

def initialize(attributes={})
  @attributes = attributes.try(:symbolize_keys) || {}
  @user = Supplejack::User.new(@attributes[:user])
  self.attributes = @attributes
end

Instance Attribute Details

#api_keyObject

Returns the api_key from the UserSet or from the User which this set belongs to.



102
103
104
# File 'lib/supplejack/user_set.rb', line 102

def api_key
  @api_key
end

#errorsObject

Returns the value of attribute errors.



33
34
35
# File 'lib/supplejack/user_set.rb', line 33

def errors
  @errors
end

#userObject

Returns the value of attribute user.



33
34
35
# File 'lib/supplejack/user_set.rb', line 33

def user
  @user
end

Class Method Details

Execute a GET request to the API /sets/featured endpoint to retrieve all UserSet objects which have the :featured flag set to true

Returns:

  • (Array)

    A array of Supplejack::UserSet objects



328
329
330
331
332
333
334
335
336
337
338
339
# File 'lib/supplejack/user_set.rb', line 328

def self.featured_sets
  path = "/sets/featured"
  if Supplejack.enable_caching
    response = Rails.cache.fetch(path, expires_in: 1.day) do
      get(path)
    end
  else
    response = get(path)
  end
  sets_array = response["sets"] || []
  user_sets = sets_array.map {|attrs| new(attrs) }
end

.find(id, api_key = nil) ⇒ UserSet

Executes a GET request with the provided UserSet ID and initializes a UserSet object with the response from the API.

Returns:



290
291
292
293
294
295
296
297
298
299
300
# File 'lib/supplejack/user_set.rb', line 290

def self.find(id, api_key=nil)
  begin
    response = get("/sets/#{id}")
    attributes = response["set"] || {}
    user_set = new(attributes)
    user_set.api_key = api_key if api_key.present?
    user_set
  rescue RestClient::ResourceNotFound => e
    raise Supplejack::SetNotFound, "UserSet with ID #{id} was not found"
  end
end

.model_nameObject

This method is normally provided by ActiveModel::Naming module, but here we have to override it so that in the Supplejack Website application it behaves as if the Supplejack::UserSet class was not under the Supplejack namespace.

This is useful when using a Supplejack::UserSet object in the Rails provided routes helpers. Example:

user_set_path(@user_set)


349
350
351
# File 'lib/supplejack/user_set.rb', line 349

def self.model_name
  ActiveModel::Name.new(self, nil, "UserSet")
end

.public_sets(options = {}) ⇒ Array

Executes a GET request to the API /sets/public endpoint to retrieve all public UserSet objects.

Parameters:

  • options (Hash) (defaults to: {})

    Supported options: :page, :per_page

Options Hash (options):

  • :page (Integer)

    The page number used to paginate through the UserSet objects

  • :per_page (Integer)

    The per_page number to select the number of UserSet objects per page.

Returns:

  • (Array)

    A array of Supplejack::UserSet objects



312
313
314
315
316
317
318
319
320
321
# File 'lib/supplejack/user_set.rb', line 312

def self.public_sets(options={})
  options.reverse_merge!(page: 1, per_page: 100)
  response = get("/sets/public", options)
  sets_array = response["sets"] || []
  user_sets = sets_array.map {|attrs| new(attrs) }
  Supplejack::PaginatedCollection.new(user_sets, 
                                      options[:page].to_i, 
                                      options[:per_page].to_i, 
                                      response["total"].to_i)
end

Instance Method Details

#api_attributesHash

Return a Hash of attributes which is used to extract the relevant UserSet attributes when creating or updating a UserSet

Returns:

  • (Hash)

    A hash with field names and their values



57
58
59
60
61
62
63
64
# File 'lib/supplejack/user_set.rb', line 57

def api_attributes
  api_attributes = {}
  [:name, :description, :privacy, :priority, :tag_list, :featured, :approved].each do |attr|
    api_attributes[attr] = self.send(attr)
  end
  api_attributes[:records] = self.api_records
  api_attributes
end

#api_recordsArray

Return a array of hashes with the format: 123, position: 1 Each hash represents a Supplejack::Item within the UserSet

This array is used to send the UserSet items information to the API.

Returns:

  • (Array)

    An array of Hashes.



73
74
75
76
77
78
79
80
81
82
83
# File 'lib/supplejack/user_set.rb', line 73

def api_records
  records = self.records.is_a?(Array) ? self.records : []
  records.map do |record_hash| 
    record_hash = record_hash.try(:symbolize_keys) || {}
    if record_hash[:record_id]
      {record_id: record_hash[:record_id], position: record_hash[:position] }
    else
      nil
    end
  end.compact
end

#attributesObject



43
44
45
46
47
48
49
50
# File 'lib/supplejack/user_set.rb', line 43

def attributes
  attributes = {}
  ATTRIBUTES.each do |attribute|
    value = self.send(attribute)
    attributes[attribute] = value if value.present?
  end
  attributes
end

#attributes=(attributes) ⇒ Object

Assigns the provided attributes to the UserSet object



181
182
183
184
185
186
187
# File 'lib/supplejack/user_set.rb', line 181

def attributes=(attributes)
  attributes = attributes.try(:symbolize_keys) || {}
  attributes.each do |attr, value|
    self.send("#{attr}=", value) if ATTRIBUTES.include?(attr)
  end
  self.records = ordered_records_from_array(attributes[:ordered_records]) if attributes[:ordered_records]
end

#destroytrue, false

Executes a DELETE request to the API with the UserSet ID and the user’s api_key

Returns:

  • (true, false)

    True if the API response was successful, false if not.



229
230
231
232
233
234
235
236
237
238
239
240
241
242
# File 'lib/supplejack/user_set.rb', line 229

def destroy
  if self.new_record?
    return false
  else
    begin
      self.class.delete("/sets/#{self.id}", {api_key: self.api_key})
      Rails.cache.delete("/users/#{self.api_key}/sets") if Supplejack.enable_caching
      return true
    rescue StandardError => e
      self.errors = e.inspect
      return false
    end
  end
end

#favourite?Boolean

Returns:

  • (Boolean)


113
114
115
# File 'lib/supplejack/user_set.rb', line 113

def favourite?
  self.name == "Favourites"
end

#has_record?(record_id) ⇒ true, false

Convinience method to find out if a particular record_id is part of the UserSet

Parameters:

  • A (Integer)

    record_id

Returns:

  • (true, false)

    True if the provided record_id is part of the UserSet, false otherwise.



135
136
137
# File 'lib/supplejack/user_set.rb', line 135

def has_record?(record_id)
  !!self.items.detect {|i| i.record_id == record_id.to_i }
end

#hidden?Boolean

Returns:

  • (Boolean)


125
126
127
# File 'lib/supplejack/user_set.rb', line 125

def hidden?
  self.privacy == "hidden"
end

#itemsItemRelation

Initializes a ItemRelation class which adds behaviour to build, create and find items related to this particular UserSet instance

Returns:



90
91
92
# File 'lib/supplejack/user_set.rb', line 90

def items
  @items ||= ItemRelation.new(self)
end

#new_record?true, false

Returns if the UserSet is persisted to the API or not.

Returns:

  • (true, false)

    True if the UserSet is persisted to the API, false if not.



221
222
223
# File 'lib/supplejack/user_set.rb', line 221

def new_record?
  self.id.blank?
end

#ordered_records_from_array(record_ids) ⇒ Array

Takes an ordered Array of record_ids and converts it into a Array of Hashes which the API expects, inferring the position value from the position of the record_id in the Array.

Examples:

user_set.ordered_records_from_array([89,66]) => [{record_id: 89, position: 1}, {record_id: 66, position: 2}]

Parameters:

  • A (Array)

    array of record_ids

Returns:

  • (Array)

    A array of hashes in the format 1, position: 1



209
210
211
212
213
214
215
# File 'lib/supplejack/user_set.rb', line 209

def ordered_records_from_array(record_ids)
  records = []
  record_ids.each_with_index do |id, index|
    records << {record_id: id, position: index+1}
  end
  records
end

#owned_by?(user) ⇒ true, false

Compares the api_key of the user and the api_key assigned to the UserSet to find out if the user passed is the owner of the set.

Parameters:

Returns:

  • (true, false)

    True if the user owns the current UserSet, false if not.



280
281
282
283
# File 'lib/supplejack/user_set.rb', line 280

def owned_by?(user)
  return false if user.try(:api_key).blank? || self.api_key.blank?
  user.try(:api_key) == self.api_key
end

#persisted?Boolean

Returns:

  • (Boolean)


244
245
246
# File 'lib/supplejack/user_set.rb', line 244

def persisted?
  !new_record?
end

#priorityObject

Returns the UserSet priority which defaults to 1



96
97
98
# File 'lib/supplejack/user_set.rb', line 96

def priority
  @priority || 1
end

#private?Boolean

Returns:

  • (Boolean)


117
118
119
# File 'lib/supplejack/user_set.rb', line 117

def private?
  self.privacy == "private"
end

#public?Boolean

Returns:

  • (Boolean)


121
122
123
# File 'lib/supplejack/user_set.rb', line 121

def public?
  self.privacy == "public"
end

#reloadObject

Fetches the UserSet information from the API again, in case it had changed. This can be useful if they items for a UserSet changed and you want the relation to have the most up to date items.



252
253
254
255
256
257
258
259
# File 'lib/supplejack/user_set.rb', line 252

def reload
  begin
    self.instance_variable_set("@items", nil)
    self.attributes = self.class.get("/sets/#{self.id}")["set"]
  rescue RestClient::ResourceNotFound => e
    raise Supplejack::SetNotFound, "UserSet with ID #{id} was not found"
  end
end

#savetrue, false

Executes a POST request when the UserSet hasn’t been persisted to the API, otherwise it executes a PUT request.

When the API returns a error response, the errors are available through the UserSet#errors virtual attribute.

Returns:

  • (true, false)

    True if the API response was successful, false if not.



154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
# File 'lib/supplejack/user_set.rb', line 154

def save
  begin
    if self.new_record?
      response = self.class.post("/sets", {api_key: self.api_key}, {set: self.api_attributes})
      self.id = response["set"]["id"]
    else
      self.class.put("/sets/#{self.id}", {api_key: self.api_key}, {set: self.api_attributes})
    end
    Rails.cache.delete("/users/#{self.api_key}/sets") if Supplejack.enable_caching
    return true
  rescue StandardError => e
    self.errors = e.inspect
    return false
  end
end

#set_record_idIntger?

Returns the record id of the associated record in a safe manner

Returns:

  • (Intger, nil)

    the record id if it exists, false otherwise



142
143
144
# File 'lib/supplejack/user_set.rb', line 142

def set_record_id
  self.record['record_id'] if self.record
end

#tag_listObject

Returns a comma separated list of tags for this UserSet



108
109
110
111
# File 'lib/supplejack/user_set.rb', line 108

def tag_list
  return @tag_list if @tag_list
  self.tags.join(', ') if self.tags
end

#update_attributes(attributes = {}) ⇒ true, false

Updates the UserSet attributes and persists it to the API

Returns:

  • (true, false)

    True if the API response was successful, false if not.



174
175
176
177
# File 'lib/supplejack/user_set.rb', line 174

def update_attributes(attributes={})
  self.attributes = attributes
  self.save
end

#viewable_by?(user) ⇒ true, false

A UserSet is viewable by anyone if it’s public or hidden When the UserSet is private it’s only viewable by the owner.

Parameters:

Returns:

  • (true, false)

    True if the user can view the current UserSet, false if not.



268
269
270
271
# File 'lib/supplejack/user_set.rb', line 268

def viewable_by?(user)
  return true if self.public? || self.hidden?
  self.owned_by?(user)
end