Skip to content

ebollens/ruby-extend_method

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

3 Commits
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

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

About

No description, website, or topics provided.

Resources

License

Stars

Watchers

Forks

Packages

No packages published

Languages