Skip to content

Commit

Permalink
refactoring sortable_attributes
Browse files Browse the repository at this point in the history
  • Loading branch information
Dan Croak committed Dec 30, 2008
1 parent 63dfc81 commit 193ee8f
Show file tree
Hide file tree
Showing 3 changed files with 23 additions and 5 deletions.
17 changes: 15 additions & 2 deletions lib/sortable_table/app/controllers/application_controller.rb
Expand Up @@ -12,8 +12,8 @@ def self.included(base)

module ClassMethods
def sortable_attributes(*args)
mappings = args.last.is_a?(Hash) ? args.pop : {}
acceptable_columns = args.collect(&:to_s) + mappings.keys.collect(&:to_s)
mappings = pop_hash_from_list(args)
acceptable_columns = join_array_and_hash_keys(args, mappings)

define_method(:sort_order) do |*default|
direction = params[:order] == 'ascending' ? 'asc' : 'desc'
Expand All @@ -26,6 +26,19 @@ def sortable_attributes(*args)
end
end
end

def pop_hash_from_list(*args)
if args.last.is_a?(Hash)
args.pop
else
{}
end
end

def join_array_and_hash_keys(array, hash)
array.collect { |each| each.to_s } +
hash.keys.collect { |each| each.to_s }
end
end

module InstanceMethods
Expand Down
7 changes: 5 additions & 2 deletions test/rails_root/app/controllers/users_controller.rb
@@ -1,9 +1,12 @@
class UsersController < ApplicationController

sortable_attributes :name, :age, :email => 'users.email'
sortable_attributes :name,
:age,
:email,
:group => "groups.name"

def index
@users = User.find :all, :order => sort_order('ascending')
@users = User.find :all, :order => sort_order("ascending")
end

end
4 changes: 3 additions & 1 deletion test/rails_root/test/functional/users_controller_test.rb
Expand Up @@ -5,7 +5,9 @@ class UsersControllerTest < ActionController::TestCase
context "enough Users to sort" do
setup { 2.times { Factory :user } }

should_sort_by_attributes :name, :email, :age do |sort, order|
should_sort_by_attributes(:name,
:age,
:email) do |sort, order|
get :index, :sort => sort, :order => order
end

Expand Down

0 comments on commit 193ee8f

Please sign in to comment.