Class: RailsCoreExtensions::Sortable
- Inherits:
-
Object
- Object
- RailsCoreExtensions::Sortable
- Defined in:
- lib/rails_core_extensions/sortable.rb
Instance Method Summary collapse
-
#initialize(params, controller_name) ⇒ Sortable
constructor
params is either: SIMPLE: model_body (where model is the model name) SCOPED: scope (name of the scope, e.g. category_id) category_id (or whatever the name of scope is) model_1_body (or whatever id of scope id).
- #sort ⇒ Object
Constructor Details
#initialize(params, controller_name) ⇒ Sortable
params is either: SIMPLE:
model_body (where model is the model name)
SCOPED:
scope (name of the scope, e.g. category_id)
category_id (or whatever the name of scope is)
model_1_body (or whatever id of scope id)
10 11 12 13 14 |
# File 'lib/rails_core_extensions/sortable.rb', line 10 def initialize(params, controller_name) @params = params.permit!.to_h.symbolize_keys @controller_name = controller_name @klass = controller_name.classify.constantize end |
Instance Method Details
#sort ⇒ Object
16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 |
# File 'lib/rails_core_extensions/sortable.rb', line 16 def sort scope = @params[:scope].try(:to_sym) @params[scope] = nil if @params[scope].blank? body_key = @controller_name.singularize + (@params[scope] ? "_#{@params[scope]}" : '') sorted_id_list = @params["#{body_key}_body".to_sym] if sorted_id_list.blank? sorted_id_list = @params["#{scope.to_s.gsub('_id', '')}_#{@params[scope]}_body".to_sym] end collection = @klass.reorder(:position) collection = collection.where(@params.slice(scope)) unless scope.blank? sort_collection(collection.find(sorted_id_list.map(&:to_i)), sorted_id_list.map(&:to_i)) end |