Skip to content

Instantly share code, notes, and snippets.

@ravinggenius
Created December 13, 2013 01:06
Show Gist options
  • Save ravinggenius/7938433 to your computer and use it in GitHub Desktop.
Save ravinggenius/7938433 to your computer and use it in GitHub Desktop.
# USAGE
class Foo < Struct.new(:name, :address)
extend HelperMacros
compare_by :name
order_by :address, :name
end
module HelperMacros
def compare_by(*accessors)
define_method(:==) do |other|
accessors.all? do |message|
send(message) == other.send(message)
end
end
end
def order_by(*accessors)
define_method(:<=>) do |other|
accessors.inject(0) do |memo, message|
if memo.zero?
result = send(message) <=> other.send(message)
result <=> memo
else
memo
end
end
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment