Skip to content

Instantly share code, notes, and snippets.

@robdimarco
Forked from r38y/loads_presenter.rb
Created September 29, 2011 00:58
Show Gist options
  • Save robdimarco/1249739 to your computer and use it in GitHub Desktop.
Save robdimarco/1249739 to your computer and use it in GitHub Desktop.
Custom sorting rules and presenters
class LoadsPresenter
extend ActiveSupport::Memoizable
def loads; raise "Implement #loads in subclass"; end
memoize :loads
def each(&block)
loads.each(&block)
end
def class
Load
end
end
class ScheduledLoadsPresenter < LoadsPresenter
def loads
Load.scheduled.eager.map{ |l| LoadPresenter.new(l) }.sort{|x, y|
sort_with_custom_rules(comparators, x, y)
}
end
def comparators
[sort_by_val_proc(:deliver_on),
Proc.new{|x,y|
load_type_order = %w(Hauling Wholesale Home Vacation)
x_index = load_type_order.index(x.load_type_name)
y_index = load_type_order.index(y.load_type_name)
x_index <=> y_index
},
sort_by_val_proc(:customer_name),
sort_by_val_proc(:destination_name),
sort_by_val_proc(:supplier_name)]
end
private
def sort_by_val_proc(field_name)
Proc.new{|x,y|x.send(field_name) <=> y.send(field_name)}
end
def sort_with_custom_rules(comparators, x, y)
comparators.each{|c| result = c.call(x, y); return result unless result.zero? }
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment