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, patch, post, put

Constructor Details

#initialize(attributes = {}) ⇒ UserSet

Returns a new instance of UserSet.



39
40
41
42
43
# File 'lib/supplejack/user_set.rb', line 39

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.



104
105
106
# File 'lib/supplejack/user_set.rb', line 104

def api_key
  @api_key
end

#errorsObject

Returns the value of attribute errors.



35
36
37
# File 'lib/supplejack/user_set.rb', line 35

def errors
  @errors
end

#userObject

Returns the value of attribute user.



35
36
37
# File 'lib/supplejack/user_set.rb', line 35

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



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

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, params = {}) ⇒ UserSet

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

Returns:



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

def self.find(id, api_key=nil, params={})
  begin
    response = get("/sets/#{id}", params)
    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)


351
352
353
# File 'lib/supplejack/user_set.rb', line 351

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



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

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



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

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.



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

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



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

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



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

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.



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

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.message
      return false
    end
  end
end

#favourite?Boolean

Returns:

  • (Boolean)


115
116
117
# File 'lib/supplejack/user_set.rb', line 115

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.



137
138
139
# File 'lib/supplejack/user_set.rb', line 137

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

#hidden?Boolean

Returns:

  • (Boolean)


127
128
129
# File 'lib/supplejack/user_set.rb', line 127

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:



92
93
94
# File 'lib/supplejack/user_set.rb', line 92

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.



223
224
225
# File 'lib/supplejack/user_set.rb', line 223

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



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

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.



282
283
284
285
# File 'lib/supplejack/user_set.rb', line 282

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)


246
247
248
# File 'lib/supplejack/user_set.rb', line 246

def persisted?
  !new_record?
end

#priorityObject

Returns the UserSet priority which defaults to 1



98
99
100
# File 'lib/supplejack/user_set.rb', line 98

def priority
  @priority || 1
end

#private?Boolean

Returns:

  • (Boolean)


119
120
121
# File 'lib/supplejack/user_set.rb', line 119

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

#public?Boolean

Returns:

  • (Boolean)


123
124
125
# File 'lib/supplejack/user_set.rb', line 123

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.



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

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.



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

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.message
    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



144
145
146
# File 'lib/supplejack/user_set.rb', line 144

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

#tag_listObject

Returns a comma separated list of tags for this UserSet



110
111
112
113
# File 'lib/supplejack/user_set.rb', line 110

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.



176
177
178
179
# File 'lib/supplejack/user_set.rb', line 176

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.



270
271
272
273
# File 'lib/supplejack/user_set.rb', line 270

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