Module: FlagShihTzu::ClassMethods

Defined in:
lib/flag_shih_tzu.rb

Instance Method Summary collapse

Instance Method Details

#chained_flags_condition(colmn = DEFAULT_COLUMN_NAME, *args) ⇒ Object


293
294
295
# File 'lib/flag_shih_tzu.rb', line 293

def chained_flags_condition(colmn = DEFAULT_COLUMN_NAME, *args)
  %[(#{flag_full_column_name(table_name, colmn)} in (#{chained_flags_values(colmn, *args).join(",")}))]
end

#chained_flags_with(column = DEFAULT_COLUMN_NAME, *args) ⇒ Object


285
286
287
288
289
290
291
# File 'lib/flag_shih_tzu.rb', line 285

def chained_flags_with(column = DEFAULT_COLUMN_NAME, *args)
  if (ActiveRecord::VERSION::MAJOR >= 3)
    where(chained_flags_condition(column, *args))
  else
    all(conditions: chained_flags_condition(column, *args))
  end
end

#check_flag(flag, colmn) ⇒ Object


257
258
259
260
261
262
263
264
265
266
# File 'lib/flag_shih_tzu.rb', line 257

def check_flag(flag, colmn)
  unless colmn.is_a?(String)
    raise ArgumentError,
          %[Column name "#{colmn}" for flag "#{flag}" is not a string]
  end
  if flag_mapping[colmn].nil? || !flag_mapping[colmn].include?(flag)
    raise ArgumentError,
          %[Invalid flag "#{flag}"]
  end
end

#determine_flag_colmn_for(flag) ⇒ Object


275
276
277
278
279
280
281
282
283
# File 'lib/flag_shih_tzu.rb', line 275

def determine_flag_colmn_for(flag)
  return DEFAULT_COLUMN_NAME if flag_mapping.nil?
  flag_mapping.each_pair do |colmn, mapping|
    return colmn if mapping.include?(flag)
  end
  raise NoSuchFlagException.new(
    %[determine_flag_colmn_for: Couldn't determine column for your flags!]
  )
end

#flag_keys(colmn = DEFAULT_COLUMN_NAME) ⇒ Object


297
298
299
# File 'lib/flag_shih_tzu.rb', line 297

def flag_keys(colmn = DEFAULT_COLUMN_NAME)
  flag_mapping[colmn].keys
end

#has_flags(*args) ⇒ Object


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
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
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
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
# File 'lib/flag_shih_tzu.rb', line 24

def has_flags(*args)
  flag_hash, opts = parse_flag_options(*args)
  opts =
    {
      named_scopes: true,
      column: DEFAULT_COLUMN_NAME,
      flag_query_mode: :in_list, # or :bit_operator
      strict: false,
      check_for_column: true
    }.update(opts)
  if !valid_flag_column_name?(opts[:column])
    warn %[FlagShihTzu says: Please use a String to designate column names! I see you here: #{caller.first}]
    opts[:column] = opts[:column].to_s
  end
  colmn = opts[:column]
  if opts[:check_for_column] && (active_record_class? && !check_flag_column(colmn))
    warn(
      %[FlagShihTzu says: Flag column #{colmn} appears to be missing!
To turn off this warning set check_for_column: false in has_flags definition here: #{caller.first}]
    )
    return
  end

  # options are stored in a class level hash and apply per-column
  self.flag_options ||= {}
  flag_options[colmn] = opts

  # the mappings are stored in this class level hash and apply per-column
  self.flag_mapping ||= {}
  # If we already have an instance of the same column in the flag_mapping,
  #   then there is a double definition on a column
  if opts[:strict] && !self.flag_mapping[colmn].nil?
    raise DuplicateFlagColumnException
  end
  flag_mapping[colmn] ||= {}

  # keep track of which flag columns are defined on this class
  self.flag_columns ||= []
  self.flag_columns << colmn

  flag_hash.each do |flag_key, flag_name|
    unless valid_flag_key?(flag_key)
      raise ArgumentError,
            %[has_flags: flag keys should be positive integers, and #{flag_key} is not]
    end
    unless valid_flag_name?(flag_name)
      raise ArgumentError,
            %[has_flags: flag names should be symbols, and #{flag_name} is not]
    end
    # next if method already defined by flag_shih_tzu
    next if flag_mapping[colmn][flag_name] & (1 << (flag_key - 1))
    if method_defined?(flag_name)
      raise ArgumentError,
            %[has_flags: flag name #{flag_name} already defined, please choose different name]
    end

    flag_mapping[colmn][flag_name] = 1 << (flag_key - 1)

    class_eval <<-EVAL, __FILE__, __LINE__ + 1
      def #{flag_name}
        flag_enabled?(:#{flag_name}, "#{colmn}")
      end
      alias :#{flag_name}? :#{flag_name}

      def #{flag_name}=(value)
        FlagShihTzu::TRUE_VALUES.include?(value) ?
          enable_flag(:#{flag_name}, "#{colmn}") :
          disable_flag(:#{flag_name}, "#{colmn}")
      end

      def not_#{flag_name}
        !#{flag_name}
      end
      alias :not_#{flag_name}? :not_#{flag_name}

      def not_#{flag_name}=(value)
        FlagShihTzu::TRUE_VALUES.include?(value) ?
          disable_flag(:#{flag_name}, "#{colmn}") :
          enable_flag(:#{flag_name}, "#{colmn}")
      end

      def #{flag_name}_changed?
        if colmn_changes = changes["#{colmn}"]
          flag_bit = self.class.flag_mapping["#{colmn}"][:#{flag_name}]
          (colmn_changes[0] & flag_bit) != (colmn_changes[1] & flag_bit)
        else
          false
        end
      end

    EVAL

    if active_record_class?
      class_eval <<-EVAL, __FILE__, __LINE__ + 1
        def self.#{flag_name}_condition(options = {})
          sql_condition_for_flag(
            :#{flag_name},
            "#{colmn}",
            true,
            options[:table_alias] || table_name
          )
        end

        def self.not_#{flag_name}_condition
          sql_condition_for_flag(:#{flag_name}, "#{colmn}", false)
        end

        def self.set_#{flag_name}_sql
          sql_set_for_flag(:#{flag_name}, "#{colmn}", true)
        end

        def self.unset_#{flag_name}_sql
          sql_set_for_flag(:#{flag_name}, "#{colmn}", false)
        end

        def self.#{colmn.singularize}_values_for(*flag_names)
          values = []
          flag_names.each do |flag_name|
            if respond_to?(flag_name)
              values_for_flag = send(:sql_in_for_flag, flag_name, "#{colmn}")
              values = if values.present?
                values & values_for_flag
              else
                values_for_flag
              end
            end
          end

          values.sort
        end
      EVAL

      # Define the named scopes if the user wants them and AR supports it
      if flag_options[colmn][:named_scopes]
        if ActiveRecord::VERSION::MAJOR == 2 && respond_to?(:named_scope)
          class_eval <<-EVAL, __FILE__, __LINE__ + 1
            named_scope :#{flag_name}, lambda {
              { conditions: #{flag_name}_condition }
            }
            named_scope :not_#{flag_name}, lambda {
              { conditions: not_#{flag_name}_condition }
            }
          EVAL
        elsif respond_to?(:scope)
          # Prevent deprecation notices on Rails 3
          #   when using +named_scope+ instead of +scope+.
          # Prevent deprecation notices on Rails 4
          #   when using +conditions+ instead of +where+.
          class_eval <<-EVAL, __FILE__, __LINE__ + 1
            scope :#{flag_name}, lambda {
              where(#{flag_name}_condition)
            }
            scope :not_#{flag_name}, lambda {
              where(not_#{flag_name}_condition)
            }
          EVAL
        end
      end

      if method_defined?(:saved_changes)
        class_eval <<-EVAL, __FILE__, __LINE__ + 1
          def saved_change_to_#{flag_name}?
            if colmn_changes = saved_changes["#{colmn}"]
              flag_bit = self.class.flag_mapping["#{colmn}"][:#{flag_name}]
              (colmn_changes[0] & flag_bit) != (colmn_changes[1] & flag_bit)
            else
              false
            end
          end
        EVAL
      end
    end

    if colmn != DEFAULT_COLUMN_NAME
      class_eval <<-EVAL, __FILE__, __LINE__ + 1

        def all_#{colmn}
          all_flags("#{colmn}")
        end

        def selected_#{colmn}
          selected_flags("#{colmn}")
        end

        def select_all_#{colmn}
          select_all_flags("#{colmn}")
        end

        def unselect_all_#{colmn}
          unselect_all_flags("#{colmn}")
        end

        # useful for a form builder
        def selected_#{colmn}=(chosen_flags)
          unselect_all_flags("#{colmn}")
          return if chosen_flags.nil?
          chosen_flags.each do |selected_flag|
            enable_flag(selected_flag.to_sym, "#{colmn}") if selected_flag.present?
          end
        end

        def has_#{colmn.singularize}?
          not selected_#{colmn}.empty?
        end

        def chained_#{colmn}_with_signature(*args)
          chained_flags_with_signature("#{colmn}", *args)
        end

        def as_#{colmn.singularize}_collection(*args)
          as_flag_collection("#{colmn}", *args)
        end

      EVAL
    end

    # Define bang methods when requested
    if flag_options[colmn][:bang_methods]
      class_eval <<-EVAL, __FILE__, __LINE__ + 1
        def #{flag_name}!
          enable_flag(:#{flag_name}, "#{colmn}")
        end

        def not_#{flag_name}!
          disable_flag(:#{flag_name}, "#{colmn}")
        end
      EVAL
    end

  end

end

#set_flag_sql(flag, value, colmn = nil, custom_table_name = table_name) ⇒ Object

Returns SQL statement to enable/disable flag. Automatically determines the correct column.


270
271
272
273
# File 'lib/flag_shih_tzu.rb', line 270

def set_flag_sql(flag, value, colmn = nil, custom_table_name = table_name)
  colmn = determine_flag_colmn_for(flag) if colmn.nil?
  sql_set_for_flag(flag, colmn, value, custom_table_name)
end