Skip to content

Instantly share code, notes, and snippets.

@skyriser
Last active December 12, 2015 10:39
Show Gist options
  • Save skyriser/4760695 to your computer and use it in GitHub Desktop.
Save skyriser/4760695 to your computer and use it in GitHub Desktop.
汎用ソートモジュール Sortable (for ActiveRecord)

汎用ソートモジュールSortable for Rails 3.2

ActiveRecordのModelに include することで簡単にソート順(order)を指定できるようになります。 すごく複雑な条件とかは全然考慮してません。

使い方

Railsなら上記の sortable.rblib に配置。 ActiveRecordを継承したModelに対して include を行います。

class User < ActiveRecord::Base
  include Sortable
end

次にソート順を指定します。

class User < ActiveRecord::Base
  include Sortable

  # 単体キー
  sortable :created_at
  # 単体キーで別名にしたい場合
  sortable :time, :created_at
  # 複合キー
  sortable :name_kana, [:last_name_kana, :first_name_kana]
end

以下のような組み合わせで検索指定が可能。

# ORDER BY created_at DESC
User.sort(:created_at, "down")

# ORDER BY created_at ASC
User.sort(:time, "up")

# ORDER BY last_name_kana DESC, first_name_kana DESC
User.sort(:name_kana, "down")
module Sortable
def self.included(klass)
klass.extend(ClassMethods)
end
module ClassMethods
@@sort_columns = {}
#
# ソート対象に追加
#
def sortable(key_name, col_name = nil)
col_name = key_name if col_name.nil?
col_name = [col_name] unless col_name.kind_of?(Array)
@@sort_columns[key_name] = col_name
end
#
# ソート順を得る (up/downを指定)
#
def sort_order(direction)
(direction == "down") ? "desc" : "asc"
end
#
# ソート条件の追加
#
def sort(key, direction)
key = key.to_sym if key.kind_of?(String)
if @@sort_columns.include?(key)
order = sort_order(direction)
columns = @@sort_columns[key].map { |col| "#{col.to_s} #{order}" }
self.order(columns.join(", "))
else
self.order
end
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment