refactor bit flags code

This commit is contained in:
r888888888
2015-07-31 16:20:36 -07:00
parent 0f6356c9e3
commit bf6dd87df8
3 changed files with 59 additions and 57 deletions

View File

@@ -0,0 +1,33 @@
module Danbooru
module HasBitFlags
extend ActiveSupport::Concern
module ClassMethods
# NOTE: the ordering of attributes has to be fixed#
# new attributes should be appended to the end.
def has_bit_flags(attributes, options = {})
field = options[:field] || :bit_flags
attributes.each.with_index do |attribute, i|
bit_flag = 1 << i
define_method(attribute) do
send(field) & bit_flag > 0
end
define_method("#{attribute}?") do
send(field) & bit_flag > 0
end
define_method("#{attribute}=") do |val|
if val.to_s =~ /t|1|y/
send("#{field}=", send(field) | bit_flag)
else
send("#{field}=", send(field) & ~bit_flag)
end
end
end
end
end
end
end