Class: Spree::Preferences::PreferenceDefinition

Inherits:
Object
  • Object
show all
Defined in:
lib/spree_core/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:



9
10
11
12
13
14
15
16
17
# File 'lib/spree_core/preferences/preference_definition.rb', line 9

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



26
27
28
# File 'lib/spree_core/preferences/preference_definition.rb', line 26

def default_value
  @column.default
end

#nameObject

The attribute which is being preferenced



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

def name
  @column.name
end

#query(value) ⇒ Object

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



40
41
42
43
44
45
46
47
48
49
50
# File 'lib/spree_core/preferences/preference_definition.rb', line 40

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

#type_cast(value) ⇒ Object

Typecasts the value based on the type of preference that was defined



31
32
33
34
35
36
37
# File 'lib/spree_core/preferences/preference_definition.rb', line 31

def type_cast(value)
  if @type == 'any'
    value
  else
    @column.type_cast(value)
  end
end