-
-
Save robdimarco/1249739 to your computer and use it in GitHub Desktop.
Custom sorting rules and presenters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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