daily pastebin goal
13%
SHARE
TWEET

Untitled

a guest Feb 19th, 2019 67 Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. module Orderable
  2.   def self.included(mod)
  3.     class << mod
  4.       include Orderable::ClassMethods
  5.     end
  6.  
  7.     mod.class_eval do
  8.       # orderable scope takes an array of sorts of the form [(key | [key, dir])*]
  9.       # and sorts the collection by the given keys
  10.       scope :orderable, lambda{|orders|
  11.         self.order(self.orders_string(orders)) if !orders.blank?
  12.       }
  13.     end
  14.   end
  15.  
  16.   module ClassMethods
  17.     def order_by(*cols)
  18.       cols.each{|col| orderable_by << col.to_s}
  19.     end
  20.  
  21.     def orderable_by
  22.       @orderable_by ||= []
  23.     end
  24.  
  25.     def order_string(col, dir)
  26.       col.to_s + (( dir && dir.to_s =~ /^d(?:esc)?$/i ) ? " desc" : "")
  27.     end
  28.  
  29.     def selected_orders(orders)
  30.       if orders
  31.         orders.split(%r{ |\+}).
  32.           map{|order| order.split("/") if order }.
  33.           reject{|col,dir| !orderable_by.include?(col.to_s)}
  34.       else
  35.         []
  36.       end
  37.     end
  38.  
  39.     def orders_string(orders)
  40.       selected_orders(orders).
  41.         map{|(col,dir)| order_string(col,dir)}.join(",")
  42.     end
  43.   end
  44. end
RAW Paste Data
We use cookies for various purposes including analytics. By continuing to use Pastebin, you agree to our use of cookies as described in the Cookies Policy. OK, I Understand
 
Top