Skip to content

HTTPS clone URL

Subversion checkout URL

You can clone with HTTPS or Subversion.

Download ZIP
Browse files

refactoring application controller into small methods

  • Loading branch information...
commit be6da0e80ae076432b47023707becd19487260a4 1 parent 193ee8f
@croaky croaky authored
View
2  README.textile
@@ -67,7 +67,7 @@ Add some sugar for your views:
%h1 Users
%table
%tr
- = sortable_table_header :name => 'Name', :sort => 'name'
+ = sortable_table_header :name => 'Name', :sort => 'name'
= sortable_table_header :name => 'E-mail', :sort => 'email'
- @users.each do |each|
%tr
View
44 lib/sortable_table/app/controllers/application_controller.rb
@@ -2,7 +2,7 @@ module SortableTable
module App
module Controllers
module ApplicationController
-
+
def self.included(base)
base.class_eval do
include InstanceMethods
@@ -15,16 +15,7 @@ def sortable_attributes(*args)
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'
- column = params[:sort] || 'created_on'
- if params[:sort] && acceptable_columns.include?(column)
- column = mappings[column.to_sym] || column
- "#{column} #{direction}"
- else
- "#{acceptable_columns.first} #{default_sort_direction(default)}"
- end
- end
+ define_sort_order(acceptable_columns, mappings)
end
def pop_hash_from_list(*args)
@@ -39,16 +30,41 @@ def join_array_and_hash_keys(array, hash)
array.collect { |each| each.to_s } +
hash.keys.collect { |each| each.to_s }
end
+
+ def define_sort_order(acceptable_columns, mappings)
+ define_method(:sort_order) do |*default|
+ direction = params[:order] == 'ascending' ? 'asc' : 'desc'
+ column = params[:sort] || 'created_on'
+ if params[:sort] && acceptable_columns.include?(column)
+ column = mappings[column.to_sym] || column
+ "#{column} #{direction}"
+ else
+ "#{acceptable_columns.first} #{default_sort_direction(default)}"
+ end
+ end
+ end
end
module InstanceMethods
def default_sort_direction(default)
- if default.any? && default.first.is_a?(Hash) && default.first.has_key?(:default)
- default.first[:default] == 'ascending' ? 'asc' : 'desc'
+ if hash_with_default_key?(default)
+ case default.first[:default]
+ when "ascending", "asc" then "asc"
+ when "descending", "asc" then "desc"
+ else
+ raise RuntimeError,
+ "valid sort orders are 'ascending' & 'descending'"
+ end
else
- 'desc'
+ "desc"
end
end
+
+ def hash_with_default_key?(object)
+ object.any? &&
+ object.first.is_a?(Hash) &&
+ object.first.has_key?(:default)
+ end
end
end
Please sign in to comment.
Something went wrong with that request. Please try again.