module ActivemodelFlags::HasFlags::ClassMethods
Public Class Methods
flags_used()
click to toggle source
# File lib/activemodel_flags/has_flags.rb, line 40 def self.flags_used all_flags = {} self.that_have_any_flags.each do |obj| obj.flags.keys.each do |key| all_flags[key] = true unless all_flags[key] end end all_flags.keys end
reset_all_flags!()
click to toggle source
# File lib/activemodel_flags/has_flags.rb, line 64 def self.reset_all_flags! self.update_all(flags: '{}') end
reset_flags!(flag)
click to toggle source
# File lib/activemodel_flags/has_flags.rb, line 52 def self.reset_flags!(flag) self.update_all("flags = REPLACE(\ REPLACE(\ REPLACE(\ REPLACE( flags, '\"#{flag}\":false', ''\ ), '\"#{flag}\":false,', ''\ ), '\"#{flag}\":true,', ''\ ), '\"#{flag}\":true', ''\ )") end
Public Instance Methods
has_flags()
click to toggle source
This will add the ability for the model to set and read flags. @note: The model must have the 'flags' column. Use rails g activemodel_flags:column model_name to generate the migration for the flags column
# File lib/activemodel_flags/has_flags.rb, line 12 def has_flags include LocalInstanceMethods serialize :flags, JSON before_create :init_flags after_initialize :init_flags scope :that_have?, -> (key) { where("#{table_name}.flags LIKE '%\"#{key}\":true%'") } scope :that_havent?, -> (key) { where("#{table_name}.flags NOT LIKE '%\"#{key}\":true%'") } scope :that_have_not?, -> (key) { that_havent?(key) } scope :that_have_any_flags, -> { where("#{table_name}.flags != '{}' AND #{table_name}.flags IS NOT NULL") } scope :all_have!, -> (flag) { self.reset_flags!(flag) self.update_all("flags = REPLACE(#{table_name}.flags, '}', '\"#{flag}\":true}')") } scope :all_have_not!, -> (flag) { self.reset_flags!(flag) self.update_all("flags = REPLACE(#{table_name}.flags, '}', '\"#{flag}\":false}')") } def self.flags_used all_flags = {} self.that_have_any_flags.each do |obj| obj.flags.keys.each do |key| all_flags[key] = true unless all_flags[key] end end all_flags.keys end def self.reset_flags!(flag) self.update_all("flags = REPLACE(\ REPLACE(\ REPLACE(\ REPLACE( flags, '\"#{flag}\":false', ''\ ), '\"#{flag}\":false,', ''\ ), '\"#{flag}\":true,', ''\ ), '\"#{flag}\":true', ''\ )") end def self.reset_all_flags! self.update_all(flags: '{}') end end