Module: ActsAsRankedList::ActiveRecord::RankColumn

Defined in:
lib/acts_as_ranked_list/active_record/rank_column.rb

Class Method Summary collapse

Class Method Details

.call(caller_class, rank_column, touch_on_update, step_increment, avoid_collisions, new_item_at, scopes) ⇒ Object

Sets the methods to rank ::ActiveRecord objects. Please refer to the README file for usage and examples.



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
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
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
# File 'lib/acts_as_ranked_list/active_record/rank_column.rb', line 8

def self.call(caller_class, rank_column, touch_on_update, step_increment, avoid_collisions, new_item_at, scopes)
  caller_class.class_eval do

    private

    define_singleton_method :scope_query do
      @scope_query ||= 
        begin
          @named_scopes = []
          scopes.map do |key, value|
            case value
            when ::Symbol
              if respond_to?(value)
                @named_scopes << value
                next
              end
              "#{caller_class.quoted_table_name}.#{connection.quote_column_name(key)} = \"#{value}\""
            when ::String, ::Integer, ::TrueClass, ::FalseClass, ::Float
              "#{caller_class.quoted_table_name}.#{connection.quote_column_name(key)} = \"#{value}\""
            when nil
              casted_key = key.to_s
              key_column_name = column_names.include?(casted_key) ? casted_key : "#{casted_key}_id"

              @grouped_scopes ||= []
              @grouped_scopes << key_column_name.to_sym
              next
            when ::Proc
              called_value = value.call
              if called_value.is_a?(::String)
                next called_value
              else
                @anonymous_scopes ||= all
                @anonymous_scopes.merge!(called_value)
                next
              end
            end
          end.compact.join(" AND ") || "1 = 1"
        end
    end
    scope_query # initializes variables

    define_singleton_method :new_item_at do
      new_item_at
    end

    define_singleton_method :step_increment do
      step_increment
    end

    define_singleton_method :avoid_collisions= do |avoid_collisions_input|
      @avoid_collisions = avoid_collisions_input
    end
    @avoid_collisions = avoid_collisions

    define_singleton_method :avoid_collisions do
      @avoid_collisions
    end

    define_singleton_method :acts_as_ranked_list_query do
      @acts_as_ranked_list_query ||= 
        begin
          query = @named_scopes.inject(default_scoped.unscope(:select, :where).where("#{scope_query}")) do |chain, scope|
            chain.send(*scope)
          end
          query.merge!(@anonymous_scopes) if @anonymous_scopes.present?
          @named_scopes = nil
          @anonymous_scopes = nil

          query
        end
    end

    define_singleton_method :quoted_rank_column do
      @_quoted_rank_column ||= connection.quote_column_name(rank_column)
    end

    define_singleton_method :quoted_rank_column_with_table_name do
      @_quoted_rank_column_with_table_name ||= "#{caller_class.quoted_table_name}.#{quoted_rank_column}"
    end

    define_singleton_method :order_by_columns do |order = "ASC"|
      @order_by_columns ||= {}
      @order_by_columns[order] ||= "        \#{\n          [ *@grouped_scopes,\n            quoted_rank_column,\n            *quoted_timestamp_attributes_for_update_in_model,\n            primary_key\n          ].compact.join(\" \#{order}, \")\n        } \#{order}\n      ORDER_BY_COLUMNS\n    end\n\n    define_singleton_method :spread_ranks do\n      @spread_ranks_sql ||= \n        begin\n          scope_query_presence = scope_query.present? ? \"AND \#{scope_query}\" : \"\"\n          <<~SQL.squish\n            WITH ORDERED_ROW_NUMBER_CTE AS (\n              SELECT \#{caller_class.primary_key}, \n                ROW_NUMBER() OVER (ORDER BY \#{order_by_columns(\"ASC\")}) AS rn\n              FROM \#{caller_class.quoted_table_name}\n            )\n            UPDATE \#{caller_class.quoted_table_name}\n            SET \#{quoted_rank_column} = ORDERED_ROW_NUMBER_CTE.rn * \#{step_increment} \#{with_touch}\n            FROM ORDERED_ROW_NUMBER_CTE\n            WHERE \#{caller_class.quoted_table_name}.\#{caller_class.primary_key} = ORDERED_ROW_NUMBER_CTE.\#{caller_class.primary_key}\n            AND \#{quoted_rank_column_with_table_name} IS NOT NULL \#{scope_query_presence}\n          SQL\n        end\n\n      connection.execute(@spread_ranks_sql)\n    end\n\n    define_singleton_method :with_touch do\n      touch_record if touch_on_update\n    end\n\n    define_singleton_method :quoted_timestamp_attributes_for_update_in_model do\n      @_quoted_timestamp_attributes_for_update_in_model ||= timestamp_attributes_for_update_in_model.map do |attribute|\n        connection.quote_column_name(attribute)\n      end\n    end\n\n    define_singleton_method :touch_record do\n      cached_quoted_now = quoted_current_time_from_proper_timezone\n\n      quoted_timestamp_attributes_for_update_in_model.map do |attribute|\n        \", \#{attribute} = \#{cached_quoted_now}\"\n      end.join\n    end\n\n    define_singleton_method :quoted_current_time_from_proper_timezone do\n      connection.quote(connection.quoted_date(current_time_from_proper_timezone))\n    end\n\n    define_singleton_method :get_highest_items do |limit = 0|\n      @get_highest_items_query ||= acts_as_ranked_list_query\n        .where(\"\#{quoted_rank_column} IS NOT NULL\")\n        .order(order_by_columns)\n\n      return @get_highest_items_query if limit == 0\n\n      @get_highest_items_query.limit(limit)\n    end\n\n    define_singleton_method :get_lowest_items do |limit = 0|\n      @get_lowest_items_query ||= acts_as_ranked_list_query\n        .where(\"\#{quoted_rank_column} IS NOT NULL\")\n        .order(order_by_columns(\"DESC\"))\n\n      return @get_lowest_items_query if limit == 0\n\n      @get_lowest_items_query.limit(limit)\n    end\n  end\n\n  caller_class.class_eval do\n    define_method :rank_column do\n      rank_column\n    end\n\n    define_method :\"\#{rank_column}=\" do |rank|\n      self[rank_column] = rank\n      @rank_changed = true\n    end\n\n    define_method :current_rank do\n      self[rank_column]\n    end\n\n    define_method :rank_changed? do\n      @rank_changed\n    end\n\n    define_method :is_ranked? do\n      self[rank_column].present?\n    end\n\n    define_method :swap_rank_with do |item|\n      temp_rank = current_rank\n      with_persistence([self, item]) do\n        self[rank_column] = item.current_rank\n        item[rank_column] = temp_rank\n      end\n    end\n\n    define_method :set_rank_between do |item_a, item_b|\n      set_rank_below(item_a)\n    end\n\n    define_method :set_rank_above do |item|\n      higher_items = get_higher_items(2, \"DESC\", item.current_rank, true, true)\n      # TODO: Why is higher_items and lower_items sometimes need to be converted to array.\n      # Is it related to if items are not found? Otherwise it returns an error\n      padded_array = pad_array(higher_items.to_a.pluck(rank_column), 0)\n      new_rank = padded_array.sum / 2\n\n      with_persistence do\n        self[rank_column] = new_rank\n      end\n    end\n\n    define_method :set_rank_below do |item|\n      # effectively the same as, without the padding of arrays\n      # sql = <<~SQL.squish\n      #   with CTE AS (\n      #     SELECT DISTINCT \#{self.class.quoted_rank_column_with_table_name} AS dis\n      #     FROM \#{caller_class.quoted_table_name}\n      #     WHERE (\#{self.class.quoted_rank_column_with_table_name} >= \#{item.current_rank}::numeric)\n      #     GROUP BY \#{self.class.quoted_rank_column_with_table_name}\n      #     ORDER BY \#{self.class.quoted_rank_column_with_table_name}\n      #     LIMIT 2\n      #   )\n      #   SELECT AVG(CTE.dis)\n      #   FROM CTE\n      # SQL\n      # new_rank = ::ActiveRecord::Base.connection.execute(sql).to_a.first.values.first\n\n      lower_items = get_lower_items(2, \"ASC\", item.current_rank, true, true)\n      padded_array = pad_array(lower_items.to_a.pluck(rank_column))\n      new_rank = padded_array.sum / 2\n\n      with_persistence do\n        self[rank_column] = new_rank\n      end\n    end\n\n    define_method :increase_rank do |count = 1|\n      higher_items = get_higher_items(count + 1, \"DESC\")\n      return if higher_items.blank?\n\n      padded_array = pad_array(higher_items.pluck(rank_column), 0)\n      new_rank = padded_array.sum / 2\n\n      with_persistence do\n        self[rank_column] = new_rank\n      end\n    end\n\n    define_method :decrease_rank do |count = 1|\n      lower_items = get_lower_items(count + 1, \"ASC\")\n      return if lower_items.blank?\n\n      padded_array = pad_array(lower_items.pluck(rank_column))\n      new_rank = padded_array.sum / 2\n\n      with_persistence do\n        self[rank_column] = new_rank\n      end\n    end\n\n    define_method :get_higher_items do |limit = 0, order = \"DESC\", rank = nil, distinct = false, include_self_rank = false|\n      return if current_rank.nil?\n\n      operator = include_self_rank ? \"<=\" : \"<\"\n      rank ||= current_rank\n\n      query = self.class.acts_as_ranked_list_query\n        .where(\"\#{self.class.quoted_rank_column} \#{operator} \#{rank}\")\n\n      self.class.instance_variable_get(:@grouped_scopes)&.each do |grouped_scope|\n        query = query.where(grouped_scope => self.send(grouped_scope))\n      end\n\n      query = query.order(self.class.order_by_columns(order))\n\n      query = query.distinct(self.class.quoted_rank_column) if distinct\n\n      return query if limit == 0\n\n      query.limit(limit)\n    end\n\n    define_method :get_lower_items do |limit = 0, order = \"ASC\", rank = nil, distinct = false, include_self_rank = false|\n      return if current_rank.nil?\n\n      operator = include_self_rank ? \">=\" : \">\"\n      rank ||= current_rank\n\n      query = self.class.acts_as_ranked_list_query\n        .where(\"\#{self.class.quoted_rank_column} \#{operator} \#{rank}\")\n\n      self.class.instance_variable_get(:@grouped_scopes)&.each do |grouped_scope|\n        query = query.where(grouped_scope => self.send(grouped_scope))\n      end\n\n      query = query.order(self.class.order_by_columns(order))\n\n      query = query.distinct(self.class.quoted_rank_column) if distinct\n\n      return query if limit == 0\n\n      query.limit(limit)\n    end\n\n    define_method :highest_item? do\n      !get_higher_items.exists?\n    end\n\n    define_method :lowest_item? do\n      !get_lower_items.exists?\n    end\n\n    private\n\n    define_method :with_persistence do |items = [self], &blk|\n      blk.call\n\n      item_record_timestamps = items.map do |i|\n        i.record_timestamps?\n      end\n\n      items.each { |i| i.record_timestamps = touch_on_update }\n\n      items.each(&:save!) unless skip_persistence?\n\n      items.each_with_index do |i, idx|\n        i.record_timestamps = item_record_timestamps[idx]\n      end\n    end\n\n    define_method :pad_array do |array, value = nil, size = 2|\n      current_array_value = array[0] || self.class.step_increment\n      value ||= current_array_value + self.class.step_increment\n      array + ::Array.new(size - array.size, value)\n    end\n  end\nend\n".squish