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 Method Summary collapse

Constructor Details

#initialize(name, *args) ⇒ PreferenceDefinition

:nodoc:



4
5
6
7
8
9
10
11
12
# File 'lib/preferences/preference_definition.rb', line 4

def initialize(name, *args) #:nodoc:
  options = args.extract_options!
  options.assert_valid_keys(:default)
  
  @type = args.first ? args.first.to_s : 'boolean'
  
  # Create a column that will be responsible for typecasting
  @column = ActiveRecord::ConnectionAdapters::Column.new(name.to_s, options[:default], @type == 'any' ? nil : @type)
end

Instance Method Details

#default_valueObject

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



21
22
23
# File 'lib/preferences/preference_definition.rb', line 21

def default_value
  @column.default
end

#nameObject

The name of the preference



15
16
17
# File 'lib/preferences/preference_definition.rb', line 15

def name
  @column.name
end

#query(value) ⇒ Object

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



33
34
35
36
37
38
39
40
41
# File 'lib/preferences/preference_definition.rb', line 33

def query(value)
  if !(value = type_cast(value))
    false
  elsif @column.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.



28
29
30
# File 'lib/preferences/preference_definition.rb', line 28

def type_cast(value)
  @type == 'any' ? value : @column.type_cast(value)
end