Module: ActiveRecord::SortableBy
- Included in:
- Base
- Defined in:
- lib/sortable_by.rb
Overview
:nodoc:
Defined Under Namespace
Class Method Summary collapse
-
.extended(base) ⇒ Object
:nodoc:.
Instance Method Summary collapse
-
#inherited(base) ⇒ Object
:nodoc:.
-
#sortable_by(*attributes, **opts) {|config| ... } ⇒ Object
Declare sortable attributes and scopes.
-
#sorted_by(expr) ⇒ ActiveRecord::Relation
The scoped relation.
Class Method Details
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
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.
181 182 183 |
# File 'lib/sortable_by.rb', line 181 def sorted_by(expr) _sortable_by_config.send :order, self, expr end |