Search code examples
javascriptjqueryruby-on-railshamltablesorter

jQuery Tablesorter File Size in Rails App


So all of my columns sort without issue, except for my Media column which displays quotas for file size limits (GB, TB, etc.) I suspect the Rails NumberHelper number_to_human_size isn't playing nicely with tablesorter. Anyone have an idea how to get it to sort, while utilizing the NumberHelper?

enter image description here

_table.html.haml

%table#myTable.tablesorter
  %thead
    %tr
      %th Name
      %th.right Per Month
      %th.right Members
      %th.right Additional
      %th.right Media
      %th.right Subscriptions

  - if @plans.any?
    %tbody
      - @plans.each do |plan|
        %tr
          %td
            = link_to admin_plan_path(plan) do
              = plan.name
          %td.right
            = "$ #{plan.base_price_in_cents / 100}"
          %td.right
            = plan.included_users
          %td.right
            = "$ #{plan.price_in_cents / 100}"
          %td.right
            = number_to_human_size(plan.media_data_quota) || '∞'.html_safe
          %td.right
            = link_to organizations_admin_plan_path(plan) do
              = plan.subscriptions.count

application.js

$(document).ready(function()
    {
        $("#myTable").tablesorter( {sortList: [[0,0], [1,0]]} );
    }
);

Solution

  • To make file sizes sort properly, you'll need a parser to convert "GB" and "TB", etc, into sortable numbers.

    There is a metric parser available on my fork of tablesorter - demo which converts both metric & binary values to make sorting work.

    To use it, load the parser file, then add a sorter-metric and data-metric-name attribute:

    <th class="sorter-metric" data-metric-name="b|byte">Media</th>
    

    I haven't tested it, but if you are using the original tablesorter, this parser should still work. If that is the case, the sorter class name won't work, so you'll need to set the headers option:

    headers: {
        0 : { sorter: 'metric' }
    }