Class: PreferenceFu::Preferences

Inherits:
Object
  • Object
show all
Includes:
Enumerable
Defined in:
lib/preference_fu.rb

Instance Attribute Summary collapse

Instance Method Summary collapse

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.preference_options
  
  # 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
  
  update_permissions
  
end

Instance Attribute Details

#instanceObject

Returns the value of attribute instance.



84
85
86
# File 'lib/preference_fu.rb', line 84

def instance
  @instance
end

#optionsObject

Returns the value of attribute options.



84
85
86
# File 'lib/preference_fu.rb', line 84

def options
  @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))
  update_permissions
end

#eachObject



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

#sizeObject



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_iObject



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