Created
December 13, 2013 01:06
-
-
Save ravinggenius/7938433 to your computer and use it in GitHub Desktop.
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
# USAGE | |
class Foo < Struct.new(:name, :address) | |
extend HelperMacros | |
compare_by :name | |
order_by :address, :name | |
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
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