Created
October 14, 2010 14:26
-
-
Save karlin/626243 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
module SetChain | |
NONDESTRUCTIVE = false | |
# Usage: | |
# foo.set_chain [:transaction, :response, :result, :score], [Transaction.new, ResponseType.new, Result.new, "42"] | |
# foo.transaction.response.result.score # => "42" | |
def set_chain(fields, values, destructive = true) | |
fields.zip(values).inject(self) do |member, (field, value)| | |
setter = "#{field}=" | |
if destructive | |
member.send setter, value | |
value | |
else | |
existing = member.send field | |
if member.send(field).nil? | |
member.send setter, value | |
value | |
else | |
existing | |
end | |
end | |
end | |
end | |
end | |
class Object | |
include SetChain | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment