Skip to content

Instantly share code, notes, and snippets.

@r38y
Created September 27, 2011 22:03
Show Gist options
  • Save r38y/1246392 to your computer and use it in GitHub Desktop.
Save r38y/1246392 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
[SortByDeliverOn, SortByLoadTypeName, SortByCustomerName, SortByDestinationName, SortBySupplierName]
end
class SortByDeliverOn
def self.compare(x, y)
x.deliver_on <=> y.deliver_on
end
end
class SortByLoadTypeName
def self.compare(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
end
end
class SortByCustomerName
def self.compare(x, y)
x.customer_name <=> y.customer_name
end
end
class SortByDestinationName
def self.compare(x, y)
x.destination_name <=> y.destination_name
end
end
class SortBySupplierName
def self.compare(x, y)
x.supplier_name <=> y.supplier_name
end
end
private
def sort_with_custom_rules(comparators, x, y)
comparators.each{|c| result = c.compare(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