Class: Preferences::PreferenceDefinition

Inherits:
Object
  • Object
show all
Defined in:
lib/preferences/preference_definition.rb

Overview

Represents the definition of a preference for a particular model

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(name, *args) ⇒ PreferenceDefinition

:nodoc:



7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
# File 'lib/preferences/preference_definition.rb', line 7

def initialize(name, *args) #:nodoc:
  options = args.extract_options!
  options.assert_valid_keys(:default, :group_defaults)
  
  @type = args.first ? args.first.to_sym : :boolean
  
  case @type
  when :any
    @klass = "ActiveRecord::Type::Value".constantize.new
  when :datetime
    @klass = "ActiveRecord::Type::DateTime".constantize.new
  else
    @klass = "ActiveRecord::Type::#{@type.to_s.classify}".constantize.new
  end

  # Create a column that will be responsible for typecasting
  @column = ActiveRecord::ConnectionAdapters::Column.new(name.to_s, options[:default], @klass)

  @group_defaults = (options[:group_defaults] || {}).inject({}) do |defaults, (group, default)|
    defaults[group.is_a?(Symbol) ? group.to_s : group] = type_cast(default)
    defaults
  end
end

Instance Attribute Details

#typeObject (readonly)

The data type for the content stored in this preference type



5
6
7
# File 'lib/preferences/preference_definition.rb', line 5

def type
  @type
end

Instance Method Details

#default_value(group = nil) ⇒ Object

The default value to use for the preference in case none have been previously defined



38
39
40
# File 'lib/preferences/preference_definition.rb', line 38

def default_value(group = nil)
  @group_defaults.include?(group) ? @group_defaults[group] : type_cast(@column.default)
end

#nameObject

The name of the preference



32
33
34
# File 'lib/preferences/preference_definition.rb', line 32

def name
  @column.name
end

#number?Boolean

Determines whether column backing this preference stores numberic values

Returns:

  • (Boolean)


43
44
45
# File 'lib/preferences/preference_definition.rb', line 43

def number?
  @column.number?
end

#query(value) ⇒ Object

Typecasts the value to true/false depending on the type of preference



57
58
59
60
61
62
63
64
65
# File 'lib/preferences/preference_definition.rb', line 57

def query(value)
  if !(value = type_cast(value))
    false
  elsif number?
    !value.zero?
  else
    !value.blank?
  end
end

#type_cast(value) ⇒ Object

Typecasts the value based on the type of preference that was defined. This uses ActiveRecord’s typecast functionality so the same rules for typecasting a model’s columns apply here.



50
51
52
53
54
# File 'lib/preferences/preference_definition.rb', line 50

def type_cast(value)
  return 1 if @type == :integer && value == true
  return 0 if @type == :integer && value == false
  @type == :any ? value : @column.type_cast_from_database(value)
end