Skip to content

Instantly share code, notes, and snippets.

@ramhoj
Created July 6, 2020 10:48
Show Gist options
  • Save ramhoj/cf4d091a2f04bb52d9aed4489ee959d0 to your computer and use it in GitHub Desktop.
Save ramhoj/cf4d091a2f04bb52d9aed4489ee959d0 to your computer and use it in GitHub Desktop.

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.

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
# 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