Class: PreferenceFu::Preferences
- Inherits:
-
Object
- Object
- PreferenceFu::Preferences
- Includes:
- Enumerable
- Defined in:
- lib/preference_fu.rb
Instance Attribute Summary collapse
-
#instance ⇒ Object
Returns the value of attribute instance.
-
#options ⇒ Object
Returns the value of attribute options.
Instance Method Summary collapse
- #[](key) ⇒ Object
- #[]=(key, value) ⇒ Object
- #each ⇒ Object
- #index(key) ⇒ Object
-
#initialize(prefs, instance) ⇒ Preferences
constructor
A new instance of Preferences.
- #size ⇒ Object
-
#store(prefs) ⇒ Object
used for mass assignment of preferences, such as a hash from params.
- #to_i ⇒ Object
Constructor Details
#initialize(prefs, instance) ⇒ Preferences
Returns a new instance of Preferences.
86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 |
# File 'lib/preference_fu.rb', line 86 def initialize(prefs, instance) @instance = instance @options = instance.class. # setup defaults if prefs is nil if prefs.nil? || @instance.new_record? @options.each do |idx, hsh| instance_variable_set("@#{hsh[:key]}", hsh[:default]) end elsif prefs.is_a?(Numeric) @options.each do |idx, hsh| instance_variable_set("@#{hsh[:key]}", (prefs & idx) != 0 ? true : false) end else raise(ArgumentError, "Input must be numeric") end end |
Instance Attribute Details
#instance ⇒ Object
Returns the value of attribute instance.
84 85 86 |
# File 'lib/preference_fu.rb', line 84 def instance @instance end |
#options ⇒ Object
Returns the value of attribute options.
84 85 86 |
# File 'lib/preference_fu.rb', line 84 def @options end |
Instance Method Details
#[](key) ⇒ Object
117 118 119 |
# File 'lib/preference_fu.rb', line 117 def [](key) instance_variable_get("@#{key}") end |
#[]=(key, value) ⇒ Object
121 122 123 124 125 |
# File 'lib/preference_fu.rb', line 121 def []=(key, value) idx, hsh = lookup(key) instance_variable_set("@#{key}", is_true(value)) end |
#each ⇒ Object
107 108 109 110 111 |
# File 'lib/preference_fu.rb', line 107 def each @options.each_value do |hsh| yield hsh[:key], self[hsh[:key]] end end |
#index(key) ⇒ Object
127 128 129 130 |
# File 'lib/preference_fu.rb', line 127 def index(key) idx, hsh = lookup(key) idx end |
#size ⇒ Object
113 114 115 |
# File 'lib/preference_fu.rb', line 113 def size @options.size end |
#store(prefs) ⇒ Object
used for mass assignment of preferences, such as a hash from params
133 134 135 136 137 |
# File 'lib/preference_fu.rb', line 133 def store(prefs) prefs.each do |key, value| self[key] = value end if prefs.respond_to?(:each) end |
#to_i ⇒ Object
139 140 141 142 143 |
# File 'lib/preference_fu.rb', line 139 def to_i @options.inject(0) do |bv, (idx, hsh)| bv |= instance_variable_get("@#{hsh[:key]}") ? idx : 0 end end |