Skip to content

Instantly share code, notes, and snippets.

@existentialmutt
Last active June 10, 2020 20:53
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save existentialmutt/f05ddd779a41ac6f47dd61f095cea1c4 to your computer and use it in GitHub Desktop.
Save existentialmutt/f05ddd779a41ac6f47dd61f095cea1c4 to your computer and use it in GitHub Desktop.
SortableList. Harness for applying SortableJS to resources generically.
-# app/views/thingies/index.haml
%table
%thead
%tr
%th
%th Thingy Name
%tbody#thingyList{data: {sortable_list_url: reorder_thingies_path} }
- @thingies.order(:position).each do |thingy|
%tr{data: {sortable_item_id: thingy.id, sortable_item: true}}
%td
%i.fas.fa-arrows-v
%td= thingy.name
:javascript
new App.SortableList(document.querySelector("#thingyList"))
# app/assets/javascripts/sortable-list.coffee
class App.SortableList
# make the provided element sortable
# the container element should have a `data-sortable-list-url` that receives the ordering
# and sortable items should have `data-sortable-id` attributes with their id
constructor: (@element) ->
@url = @element.getAttribute('data-sortable-list-url')
@_initSortable()
_initSortable: ->
Sortable.create @element,
animation: 150
onEnd: (event) =>
item_ids = $(@element)
.children("[data-sortable-item]")
.toArray()
.map (item) => item.getAttribute("data-sortable-item-id")
$.ajax
url: @url
data: {sortable_ids: item_ids}
method: 'POST'
dataType: 'text/html'
# app/controllers/concerns/sortable_resource_controller.rb
module SortableResourceController
extend ActiveSupport::Concern
def reorder
params[:sortable_ids].each_with_index do |id, i|
sortable_resource_repo.where(id: id).update_all position: i+1
end
head :ok
end
private def sortable_resource_repo
raise "Abstract Method"
end
end
# app/controllers/thingies_controller.rb
class ThingiesController < ApplicationController
include SortableResourceController
private def sortable_resource_repo
Thingy.all
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment