-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathpreference_definition.rb
59 lines (52 loc) · 1.64 KB
/
preference_definition.rb
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
# Most of this code is from the preferences plugin available at
# http://github.com/pluginaweek/preferences/tree/master
#
module Spree
# Adds support for defining preferences on ActiveRecord models.
module Preferences
# Represents the definition of a preference for a particular model
class PreferenceDefinition
def initialize(attribute, *args) #:nodoc:
options = args.extract_options!
options.assert_valid_keys(:default, :values)
@type = args.first ? args.first.to_s : 'boolean'
@values = options[:values]
# Create a column that will be responsible for typecasting
@column = ActiveRecord::ConnectionAdapters::Column.new(attribute.to_s, options[:default], @type == 'any' ? nil : @type)
end
# The attribute which is being preferenced
def attribute
@column.name
end
# The default value to use for the preference in case none have been
# previously defined
def default_value
@column.default
end
# Typecasts the value based on the type of preference that was defined
def type_cast(value)
if @type == 'any'
value
else
@column.type_cast(value)
end
end
# Typecasts the value to true/false depending on the type of preference
def query(value)
unless value = type_cast(value)
false
else
if @column.number?
!value.zero?
else
!value.blank?
end
end
end
# List of possible values that can be set for the preference.
def values
@values
end
end
end
end