Skip to content

Instantly share code, notes, and snippets.

@karlin
Created October 14, 2010 14:26
Show Gist options
  • Save karlin/626243 to your computer and use it in GitHub Desktop.
Save karlin/626243 to your computer and use it in GitHub Desktop.
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