Module: ActivemodelFlags::HasFlags::ClassMethods
- Defined in:
- lib/activemodel_flags/has_flags.rb
Class Method Summary collapse
Instance Method Summary collapse
-
#has_flags ⇒ Object
This will add the ability for the model to set and read flags.
Class Method Details
.flags_used ⇒ Object
40 41 42 43 44 45 46 47 48 49 50 |
# 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! ⇒ Object
64 65 66 |
# File 'lib/activemodel_flags/has_flags.rb', line 64 def self.reset_all_flags! self.update_all(flags: '{}') end |
.reset_flags!(flag) ⇒ Object
52 53 54 55 56 57 58 59 60 61 62 |
# 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 |
Instance Method Details
#has_flags ⇒ Object
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
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 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 |
# 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 |