Is there a way to include only certain methods from a module instead
of all the methods?
Given the following:
module ActsAsAnything
def self.included(base)
base.extend(ClassMethods)
end
module ClassMethods
def acts_as_anything(opts = {})
# Based on the options based in, I would like to selectively
include certain methods from
# the InstanceMethods module.
# Something like:
include ActsAsAnything::InstanceMethods.instance_method(:index)
if opts[:include_index]
include ActsAsAnything::InstanceMethods.instance_method(:list)
if opts[:include_list]
# (Note the 'if' condition above is just for example.... )
end
end
module InstanceMethods
def index
# …
end
def list
# …
end
end
end
However, ‘include’ requires a module and I can’t figure out the proper
syntax, or even if this is possible, to just include a certain method
from it. The is for a standard acts_as_… Rails plug-in.
Is there a way to include only certain methods from a module instead
of all the methods?
Not directly. In general, methods are part of the same module for a
reason. A given method may call other methods in the module, and a
method may use instance variables defined in other methods.
What you propose could make sense in the case of a “pure utility” module
which has no state and where there little is or no relationship between
the methods.
def methods_to_lambdas(mod)
instance = Class.new { include mod }.new
mod.instance_methods(false).inject(Hash.new) { |hash, meth|
hash.update(
meth.to_sym => lambda { |*args, &block|
instance.send(meth, *args, &block)
}
)
}
end
However, ‘include’ requires a module and I can’t figure out the proper
syntax, or even if this is possible, to just include a certain method
from it. The is for a standard acts_as_… Rails plug-in.