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

Returns a new instance of PreferenceDefinition.



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

def initialize(name, *args)
  options = args.extract_options!
  options.assert_valid_keys(:default, :group_defaults)

  @type = args.first ? args.first.to_sym : :boolean

  @klass = if type == :any
    ActiveRecord::Type::Value.new
  else
    ActiveRecord::Type.lookup(type)
  end

  @name = name.to_s
  @default = options[:default]

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

Instance Attribute Details

#nameObject (readonly)

The data type for the content stored in this preference type



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

def name
  @name
end

#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



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

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

#number?Boolean

Determines whether column backing this preference stores numeric values

Returns:

  • (Boolean)


34
35
36
# File 'lib/preferences/preference_definition.rb', line 34

def number?
  type == :integer || type == :float
end

#query(value) ⇒ Object

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



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

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.



39
40
41
42
43
44
# File 'lib/preferences/preference_definition.rb', line 39

def type_cast(value)
  return 1 if @type == :integer && value == true
  return 0 if @type == :integer && value == false

  @klass.deserialize(value)
end