Module: ActiveRecordFlagSupport::ClassMethods
- Defined in:
- lib/activerecord_flag_support.rb
Instance Method Summary collapse
-
#define_flag_methods(field, method_hash = nil) ⇒ Object
—————————————————— define_flag_methods.
Instance Method Details
#define_flag_methods(field, method_hash = nil) ⇒ Object
—————————————————— define_flag_methods
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 |
# File 'lib/activerecord_flag_support.rb', line 8 def define_flag_methods( field, method_hash = nil ) if method_hash.nil? method_hash = field field = :flags end unless method_hash.is_a?( Hash ) col = 1 method_hash = method_hash.inject( {} ) do |m,x| m[x] = col col *= 2 m end end method_hash.each_pair do |key,value| class_eval( "def #{key}\n return ( #{field} & #{value} ) == #{value}; end" ) class_eval( "def #{key}=(v)\n old_value = #{key}; set_flag( :#{field}, v, #{value} ); if old_value != #{key}\n@#{key}_was_changed = true;\nend\n end" ) class_eval( "def #{key}_changed?\n new_record? || @#{key}_was_changed\n end" ) class_eval( "def #{key}?\n return ( #{field} & #{value} ) == #{value}; end" ) class_eval( "def update_#{key}(v)\n set_flag( :#{field}, v, #{value} ); update_attribute( :#{field}, self.#{field} ); end" ) konst = "%s_MASK" % key.upcase unless const_defined?( konst ) const_set( konst, value ) end end cattr_accessor "#{field}_flag_hash" class_variable_set( "@@#{field}_flag_hash", method_hash ) unless method_defined?( :set_flag ) class_eval("include ActiveRecordFlagSupport::FlagInstanceMethods") end end |