Skip to content

Instantly share code, notes, and snippets.

@ramhoj
Created July 6, 2020 10:48
Show Gist options
  • Select an option

  • Save ramhoj/cf4d091a2f04bb52d9aed4489ee959d0 to your computer and use it in GitHub Desktop.

Select an option

Save ramhoj/cf4d091a2f04bb52d9aed4489ee959d0 to your computer and use it in GitHub Desktop.

Revisions

  1. ramhoj created this gist Jul 6, 2020.
    2 changes: 2 additions & 0 deletions README.md
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,2 @@
    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.
    21 changes: 21 additions & 0 deletions my_class.rb
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,21 @@
    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
    20 changes: 20 additions & 0 deletions prependable.rb
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,20 @@
    # 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