AroundTheWorld

A metaprogramming module which allows you to wrap any method easily.

Gem Version Build Status Maintainability Test Coverage

Installation

Add this line to your application's Gemfile:

gem "around_the_world"

And then execute:

$ bundle

Or install it yourself as:

$ gem install around_the_world

Usage

Define a method that gets called around the given instance method:

class SomeClass
  include AroundTheWorld

  def make_something_happen!
    @something_happened = true
  end

  def did_something_happened?
    !!@something_happened
  end

  around_method :make_something_happen!, :did_something_happened? do |..|
    things_happened = super(...)

    if things_happened
      "Something happened!"
    else
      "Nothing to see here..."
    end
  end
end
> SomeClass.new.did_something_happened?
=> "Nothing to see here..."

> SomeClass.new.make_something_happen!
=> "Something happened!"

> SomeClass.new.did_something_happened?
=> "Something happened!"

around_method accepts an option hash prevent_double_wrapping_for: [Object]. If defined, this prevents wrapping the method twice for a given purpose. It accepts any value:

class SomeClass
  include AroundTheWorld

  def some_method
    "method behavior"
  end

  around_method :some_method, prevent_double_wrapping_for: :memoization do |...|
    @memoized ||= super(...)
  end

  around_method :some_method, prevent_double_wrapping_for: :memoization do |...|
    @memoized ||= super(...)
  end
end

Results in:

# => AroundTheWorld::DoubleWrapError:
     "Module AroundTheWorld:ProxyModule:memoization already defines the method :some_method"

It works for class methods too:

class SomeClass
  class << self
    include AroundTheWorld

    def a_singleton_method; end

    around_method :a_singleton_method do |...|
      super(...)

      "It works for class methods too!"
    end
  end
end
> SomeClass.a_singleton_method
=> "It works for class methods too!"

Development

Consult Spicerack's development instructions for more info.

Contributing

Bug reports and pull requests are welcome on GitHub at https://github.com/RubyAfterAll/spicerack.

License

The gem is available as open source under the terms of the MIT License.