Sha256: 355987b78c136d9219c531f0f4085d31a59c566979214ad27bdcecc68e598700

Contents?: true

Size: 1.51 KB

Versions: 6

Compression:

Stored size: 1.51 KB

Contents

module RailsCoreExtensions
  class 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)
    def initialize(params, controller_name)
      @params = params.symbolize_keys
      @controller_name = controller_name
      @klass = controller_name.classify.constantize
    end

    def sort
      scope = @params[:scope].try(:to_sym)

      param_key = @controller_name.singularize
      param_key += "_#{@params[scope]}" if scope

      params_collection = @params["#{param_key}_body".to_sym]

      if params_collection.blank?
        name = "#{scope.to_s.gsub('_id', '')}_#{@params[scope]}_body".to_sym
        params_collection = @params[name]
      end

      collection = @klass.reorder(:position)
      collection = collection.where(@params.slice(scope.to_sym)) if scope

      sort_collection(collection, params_collection.map(&:to_i))
    end

    private

    def sort_collection(collection_old, collection_new_ids)
      @klass.transaction do
        collection_old.each.with_index do |object, index|
          next if object.id == collection_new_ids[index]

          new_position = collection_new_ids.index(object.id) + 1
          update(object, new_position)
        end
      end
    end

    def update(object, new_position)
      @klass.where(id: object.id).limit(1).update_all(position: new_position)
    end
  end
end

Version data entries

6 entries across 6 versions & 1 rubygems

Version Path
rails_core_extensions-0.4.0 lib/rails_core_extensions/sortable.rb
rails_core_extensions-0.3.0 lib/rails_core_extensions/sortable.rb
rails_core_extensions-0.2.0 lib/rails_core_extensions/sortable.rb
rails_core_extensions-0.1.1 lib/rails_core_extensions/sortable.rb
rails_core_extensions-0.1.0 lib/rails_core_extensions/sortable.rb
rails_core_extensions-0.0.1 lib/rails_core_extensions/sortable.rb