Class: Preference

Inherits:
ActiveRecord::Base
  • Object
show all
Defined in:
app/models/preference.rb

Overview

Represents a preferred value for a particular preference on a model.

Grouped preferences

In addition to simple named preferences, preferences can also be grouped by a particular value, be it a string or ActiveRecord object. For example, a User may have a preferred color for a particular Car. In this case, the owner is the User record, the name is “color”, and the group is the Car record. This allows preferences to have a sort of context around them.

Class Method Summary collapse

Instance Method Summary collapse

Class Method Details

.split_group(group = nil) ⇒ Object

Splits the given group into its corresponding id and type. For simple primitives, the id will be nil. For complex types, specifically ActiveRecord objects, the id is the unique identifier stored in the database for the record.

For example,

Preference.split_group('google')      # => [nil, "google"]
Preference.split_group(1)             # => [nil, 1]
Preference.split_group(User.find(1))  # => [1, "User"]


28
29
30
31
32
33
34
35
36
# File 'app/models/preference.rb', line 28

def split_group(group = nil)
  if group.is_a?(ActiveRecord::Base)
    group_id, group_type = group.id, group.class.base_class.name.to_s
  else
    group_id, group_type = nil, group.is_a?(Symbol) ? group.to_s : group
  end
  
  [group_id, group_type]
end

Instance Method Details

#definitionObject

The definition of the preference as defined in the owner’s model



40
41
42
43
44
45
# File 'app/models/preference.rb', line 40

def definition
  # Optimize number of queries to the database by only looking up the actual
  # owner record for STI cases when the definition can't be found in the
  # stored owner type class
  owner_type && (find_definition(owner_type.constantize) || find_definition(owner.class))
end

#group_with_optional_lookupObject

Only searches for the group record if the group id is specified



55
56
57
# File 'app/models/preference.rb', line 55

def group_with_optional_lookup
  group_id ? group_without_optional_lookup : group_type
end

#valueObject

Typecasts the value depending on the preference definition’s declared type



48
49
50
51
52
# File 'app/models/preference.rb', line 48

def value
  value = read_attribute(:value)
  value = definition.type_cast(value) if definition
  value
end