Skip to content

Instantly share code, notes, and snippets.

@danielfone
Last active August 29, 2015 14:06
Show Gist options
  • Save danielfone/c6633c10c789868a5a24 to your computer and use it in GitHub Desktop.
Save danielfone/c6633c10c789868a5a24 to your computer and use it in GitHub Desktop.
def temporary_assign(object, attribute, new_value)
previous_value = object.public_send attribute
object.public_send "#{attribute}=", new_value
yield
ensure
object.public_send "#{attribute}=", previous_value
end
# Example usage:
# Want to debug SQL queries in tests? Log to STDOUT just for the
# queries you want to check and avoid the noise of the test suite
temporary_assign ActiveRecord::Base, :logger, Logger.new(STDOUT) do
# Some complex AR query
if user.has_role? :admin
scope.all
else
Agency.with_roles([:manager, :user], user).uniq
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment