0.0
No commit activity in last 3 years
No release in over 3 years
Simple mechanism for extending an existing method
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
 Dependencies

Development

 Project Readme

extend_method

Dry and simple gem for method overriding in non-inheritance contexts.

Status

This implementation is a release candidate.

Gem Version Code Climate Build Status Coverage Status Dependency Status

Please report issues in the issue tracker. Pull requests are welcome.

License

The extend_method library is open-source software licensed under the BSD 3-clause license. The full text of the license may be found in the LICENSE file.

Credits

This library is written and maintained by Eric Bollens.

Usage

Require the gem:

require 'extend_method'

The extend_method class method can then be included as:

class Example

  class << self
    include ExtendMethod
  end

end

A motivating example showing some of the major features:

module Base

  def set val
    @val = val
  end

  def get
    @val
  end

end

class Extended

  include Base

  class << self
    include ExtendMethod
  end

  extend_method :set do |val|
    parent_method "#{val}!"
  end

  extend_method :get do
    "foo#{parent_method}"
  end

  extend_method :other do
    if has_parent_method?
      parent_method
    else
      # do something else
    end
  end

end

example = new Extended
example.set 'bar'
assert 'foobar!' == example.get

The extend_method class method takes a symbol for the method name and a block that extends the method, exposing the previous version of the method as parent_method:

class Example

  def basic_example
    # ..
  end

  extend_method :basic_example do
    # ..
    val = parent_method
    # ..
  end

end

To determine if a parent method exists, use the has_parent_method? method:

class Example

  extend_method :optional_parent_method_example do |*args|
    # ..
    parent_method(*args) if has_parent_method?
    # ..
  end

end

The block accepts arguments for what's passed to the method:

class Example

  extend_method :argument_example do |val|
    "foo#{parent_method val}"
  end

end