bryanwoods/including

Experiment to implement granular loading of module code in Ruby

★ 3Forks 1RubyGitHub ↗Compare

Project website ↗

README

  • An observation: Other languages allow for more granular loading of only desired methods and functions from module code.

  • An experiment: How might this be done in Ruby?

  • A warning: Running this code in production might not be wise.

Let’s say you’ve got a module:

module Foo
  def foo
    "foo"
  end

  def bar
    "bar"
  end

  def baz
    "baz"
  end
end

And you want to mix it in to a class. But wait! the foo method might conflict with some other foo!

class Bar
  including Foo, except: "foo"
end

bar = Bar.new
bar.bar # "bar"
bar.foo # NoMethodError

That’s basically it. You can pass an array of only the methods you’d like to mix in, or an array of exceptions, via except.

class Quux
  including Foo, only: [:foo, :baz]
end

quux = Quux.new
quux.foo # "foo"
quux.bar # NoMethodError
quux.baz # "baz"
gem install including

Copyright © 2012 Bryan Woods. See LICENSE.txt for further details.

Contributors

bryanwoods

Issues