Class: Oort::Scopes

Inherits:
Object
  • Object
show all
Defined in:
lib/oort/scopes.rb

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(association_class:) ⇒ Scopes

Returns a new instance of Scopes.



9
10
11
# File 'lib/oort/scopes.rb', line 9

def initialize(association_class:)
  @association_class = association_class
end

Class Method Details

.call(association_class:) ⇒ Object



5
6
7
# File 'lib/oort/scopes.rb', line 5

def self.call(association_class:)
  new(association_class: association_class).call
end

Instance Method Details

#callObject



13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
# File 'lib/oort/scopes.rb', line 13

def call
  # user = User.find(909)
  # user.posts.ordered_with(user.posts_ordered)
  # by default this will use posts.id::INTEGER
  # but you can pass in something else if you have joins and items
  # stored in another table
  @association_class.class_eval do
    scope :ordered_with, lambda { |ids, type = "#{table_name}.id::INTEGER"|
      if ids.blank?
        order(:id)
      else
        order(Arel.sql("array_position(ARRAY[#{ids.join(", ")}], #{type})"))
      end
    }
  end
end