Module: ActiveRecord::SortableBy

Included in:
Base
Defined in:
lib/sortable_by.rb

Overview

:nodoc:

Defined Under Namespace

Classes: Config, Field

Class Method Summary collapse

Instance Method Summary collapse

Class Method Details

.extended(base) ⇒ Object

:nodoc:



109
110
111
112
# File 'lib/sortable_by.rb', line 109

def self.extended(base) # :nodoc:
  base.class_attribute :_sortable_by_config, instance_accessor: false, instance_predicate: false
  base._sortable_by_config = Config.new
end

Instance Method Details

#inherited(base) ⇒ Object

:nodoc:



114
115
116
117
# File 'lib/sortable_by.rb', line 114

def inherited(base) # :nodoc:
  base._sortable_by_config = _sortable_by_config.deep_dup
  super
end

#sortable_by(*attributes, **opts) {|config| ... } ⇒ Object

Declare sortable attributes and scopes. Examples:

# Simple
class Post < ActiveRecord::Base
  sortable_by :title, :id
end

# Case-sensitive
class Post < ActiveRecord::Base
  sortable_by do |x|
    x.field :title, case_sensitive: true
    x.field :id
  end
end

# With default
class Post < ActiveRecord::Base
  sortable_by :id, :topic, :created_at,
    default: 'topic,-created_at'
end

# Composition
class App < ActiveRecord::Base
  sortable_by :name, default: '-version' do |x|
    x.field :version, as: %i[major minor patch]]
  end
end

# Associations (eager load)
class Product < ActiveRecord::Base
  belongs_to :shop

  sortable_by do |x|
    x.field :name
    x.field :shop, as: Shop.arel_table[:name], eager_load: :shop
    x.default 'shop,name'
  end
end

# Associations (custom scope)
class Product < ActiveRecord::Base
  belongs_to :shop

  sortable_by do |x|
    x.field :shop, as: Shop.arel_table[:name], scope: -> { joins(:shop) }
  end
end

Yields:

  • (config)


167
168
169
170
171
172
173
174
175
176
177
# File 'lib/sortable_by.rb', line 167

def sortable_by(*attributes, **opts)
  config  = _sortable_by_config
  default = opts.delete(:default)

  attributes.each do |name|
    config.field(name, **opts)
  end
  config.default(default) if default
  yield config if block_given?
  config
end

#sorted_by(expr) ⇒ ActiveRecord::Relation

Returns the scoped relation.

Parameters:

  • expr (String)

    the sort expr

Returns:

  • (ActiveRecord::Relation)

    the scoped relation



181
182
183
# File 'lib/sortable_by.rb', line 181

def sorted_by(expr)
  _sortable_by_config.send :order, self, expr
end