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"]


33
34
35
36
37
38
39
40
41
# File 'app/models/preference.rb', line 33

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



45
46
47
48
49
50
# File 'app/models/preference.rb', line 45

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

#groupObject



61
62
63
# File 'app/models/preference.rb', line 61

def group
  group_id ? original_group : group_type
end

#original_groupObject

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



60
# File 'app/models/preference.rb', line 60

alias_method :original_group, :group

#valueObject

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



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

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