Skip to content

Instantly share code, notes, and snippets.

@rreinhardt9
Created July 15, 2022 17:51
Show Gist options
  • Save rreinhardt9/1f7259d5a4d8d359457ecfa1e9a20fc8 to your computer and use it in GitHub Desktop.
Save rreinhardt9/1f7259d5a4d8d359457ecfa1e9a20fc8 to your computer and use it in GitHub Desktop.
Re-creating the "Suppressible" concern that was shown in this screencast from DHH: https://www.youtube.com/watch?v=m1jOWu7woKM
module Suppressible
extend ActiveSupport::Concern
class_methods do
def suppress
self.suppressed = true
yield
ensure
self.suppressed = false
end
def suppressed?
suppressed == true
end
private
attr_accessor :suppressed
end
end
@rreinhardt9
Copy link
Author

This is my best attempt so far; the actual concern wasn't shown in the screencast but I'm really interested in using a similar approach. Let me know if you see ways to improve on this!

In the screencast, DHH showed using it in the following way. Let's say I've included this concern in a Mention class:

Mention.suppressed?
=> false

Mention.suppress do
  Mention.suppressed?
end
=> true

The specific use case is so that you can suppress active record callback for times when you DON'T want the side effect to happen.

@bartimez
Copy link

One thing I'm curious about here is that this assumes we'd want to suppress all callbacks. Maybe we could do something like pass an optional argument to self.suppressed that would allow us to specify particular callbacks we didn't want to run. But, that would be vulnerable to changes in the method name

@bartimez
Copy link

Hmm, maybe the answer there is unless hooks on the specific callbacks

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment