Shortcut to prepend module that checks an argument and only calls original implementation if argument evals to false. Other versions could instead execute super(*args) and do different things depending on the result.
Created
July 6, 2020 10:48
-
-
Save ramhoj/cf4d091a2f04bb52d9aed4489ee959d0 to your computer and use it in GitHub Desktop.
This file contains hidden or 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
class MyClass | |
extend Prependable | |
define_prepend :dry, guard: -> { dry_run? }, body: ->(name) { puts "#{name} was called." } | |
dry def delete | |
MyFileUtil.copy_to_trash | |
MyFileUtil.delete_all | |
end | |
dry def move | |
MyFileUtil.copy_to_loclation | |
MyFileUtil.delete_all | |
end | |
private | |
def dry_run? | |
ENV["dry"] | |
end | |
end |
This file contains hidden or 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
# frozen_string_literal: true | |
module Prependable | |
def define_prepend(prepend_name, guard:, body:) | |
define_singleton_method(prepend_name) do |name| | |
mod = Module.new do | |
define_method(name) do |*args| | |
if instance_exec(&guard) | |
instance_exec(name, &body) | |
else | |
super(*args) | |
end | |
end | |
end | |
prepend mod | |
name | |
end | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment