Class: RankleIndex
- Inherits:
-
ActiveRecord::Base
- Object
- ActiveRecord::Base
- RankleIndex
- Includes:
- RankedModel
- Defined in:
- lib/rankle_index.rb
Class Method Summary collapse
- .position(instance, name) ⇒ Object
- .rank(instance, name, position) ⇒ Object
- .ranked(name) ⇒ Object
- .ranks(klass, ranker) ⇒ Object
- .set_default_position(instance) ⇒ Object
Class Method Details
.position(instance, name) ⇒ Object
40 41 42 43 44 45 46 |
# File 'lib/rankle_index.rb', line 40 def self.position instance, name indexable_position = where(indexable_name: name.to_s, indexable_id: instance.id, indexable_type: instance.class.to_s).first_or_create!.indexable_position indexable_scope = where(indexable_name: name.to_s) indexable_scope = indexable_scope.where(indexable_type: instance.class.to_s) if name == :default indexable_scope = indexable_scope.where('indexable_position < ?', indexable_position) indexable_scope.count end |
.rank(instance, name, position) ⇒ Object
28 29 30 31 32 33 34 35 36 37 38 |
# File 'lib/rankle_index.rb', line 28 def self.rank instance, name, position existing_indices = if name == :default RankleIndex.where indexable_name: name.to_s, indexable_type: instance.class.to_s else RankleIndex.where indexable_name: name.to_s end position = existing_indices.count - 1 if position > existing_indices.count position = 0 if position < 0 index = RankleIndex.where(indexable_name: name.to_s, indexable_id: instance.id, indexable_type: instance.class.to_s).first_or_create! index.update_attribute(:row_order_position, position) end |
.ranked(name) ⇒ Object
48 49 50 51 52 |
# File 'lib/rankle_index.rb', line 48 def self.ranked name where(indexable_name: name).order(:indexable_position).map do |duck| duck.indexable_type.classify.constantize.find(duck.indexable_id) end end |
.ranks(klass, ranker) ⇒ Object
12 13 14 |
# File 'lib/rankle_index.rb', line 12 def self.ranks klass, ranker @rankers[klass] = ranker end |
.set_default_position(instance) ⇒ Object
16 17 18 19 20 21 22 23 24 25 26 |
# File 'lib/rankle_index.rb', line 16 def self.set_default_position instance if @rankers[instance.class] && @rankers[instance.class].strategy position = instance.class.ranked.each_with_index { |record, index| break index if @rankers[instance.class].strategy.call(instance, record) } unless @rankers[instance.class].strategy.is_a?(Symbol) end position = position.count if position.is_a?(ActiveRecord::Relation) position = instance.class.count - 1 if position.nil? || position.is_a?(Array) instance.rank position if @rankers[instance.class] && @rankers[instance.class].strategy.is_a?(Symbol) instance.rank @rankers[instance.class].strategy, RankleIndex.where(indexable_name: @rankers[instance.class].strategy).count end end |