Module: HasManyBooleans::InstanceMethods

Defined in:
lib/has_many_booleans.rb

Overview

:nodoc: callbacks

Instance Method Summary collapse

Instance Method Details

#initialize_booleansObject

Load boolean integer from database and define the methods.



188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
# File 'lib/has_many_booleans.rb', line 188

def initialize_booleans
  booleans_field  = self.class.booleans_options[:field]
  booleans_activated = self[booleans_field] ? self[booleans_field].to_bra : []

  @booleans_data = { nil => [0, false] } # self@nil

  self.class.booleans_default.each{ |name, (index, value)|
    name = name.to_s

    each_suffix{ |suffix|
      # get values
      init_value = if self.new_record?
        self.class.booleans_options[:true].member?(name.to_sym)
      else
        booleans_activated.member?(index)
      end
      @booleans_data[name] = [index, init_value]

      # define the methods
      method_name = name + self.class.booleans_options[:append] + suffix
      define_boolean_method method_name, suffix, name

      # define the self method
      if self.class.booleans_options[:self]
        # get value
        if self.new_record?
          cond = self.class.booleans_options[:self_value]
        else
          cond = booleans_activated.member? 0
        end
        @booleans_data[nil][1] = cond ? true : false

        # get self method name
        self_method = if self.class.booleans_options[:self] === true
          if !self.class.booleans_options[:append] || self.class.booleans_options[:append].empty?
            raise "has_many_booleans: self method activated with true, but :append is nil! Please use :self => 'method_name'"
          else
            self.class.booleans_options[:append][1..-1]
          end
        else
          self.class.booleans_options[:self]
        end

        each_suffix{ |suffix|
          define_boolean_method self_method + suffix, suffix
        }
      end
    }
  }
end

#save_booleansObject

Transform booleans to integer and save in the database.



240
241
242
243
244
245
246
# File 'lib/has_many_booleans.rb', line 240

def save_booleans
  act = []
  @booleans_data.each{ |_, (index, value)|
    act << index if value
  }
  self[ self.class.booleans_options[:field] ] = act.to_bri
end