Sha256: a267aa0be4986de59e02db68073779a034019caebb8e9cf4a692eee5509641e2

Contents?: true

Size: 1.66 KB

Versions: 4

Compression:

Stored size: 1.66 KB

Contents

# Represents a preferred value for a particular preference on a model.
# 
# == Targeted preferences
# 
# In addition to simple named preferences, preferences can also be targeted for
# a particular record.  For example, a User may have a preferred color for a
# particular Car.  In this case, the +owner+ is the User, the +preference+ is
# the color, and the +target+ is the Car.  This allows preferences to have a sort
# of context around them.
class Preference < ActiveRecord::Base
  belongs_to  :owner,
                :polymorphic => true
  belongs_to  :group,
                :polymorphic => true
  
  validates_presence_of :attribute,
                        :owner_id,
                        :owner_type
  validates_presence_of :group_type,
                          :if => :group_id?
  
  class << self
    # Splits the given group into its corresponding id and type
    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
      end
      
      return group_id, group_type
    end
  end
  
  # The definition for the attribute
  def definition
    owner_type.constantize.preference_definitions[attribute] if owner_type
  end
  
  # Typecasts the value depending on the preference definition's declared type
  def value
    value = read_attribute(:value)
    value = definition.type_cast(value) if definition
    value
  end
  
  # Only searches for the group record if the group id is specified
  def group_with_optional_lookup
    group_id ? group_without_optional_lookup : group_type
  end
  alias_method_chain :group, :optional_lookup
end

Version data entries

4 entries across 4 versions & 1 rubygems

Version Path
preferences-0.1.0 app/models/preference.rb
preferences-0.1.1 app/models/preference.rb
preferences-0.1.2 app/models/preference.rb
preferences-0.1.3 app/models/preference.rb