Suppose I have a module with the methods : function1,function2,function3. I want to import function1 and function2 but not function3. Is there a way to do this in ruby?
+4
A:
Not sure if there is a clean way to just add the methods you want, but you can remove the methods that you don't want by using undef_method
.
module Foo
def function1
end
def function2
end
def function3
end
end
module MiniFoo
include Foo
not_wanted_methods = Foo.instance_methods - %w(function1 function2)
not_wanted_methods.each {|m| undef_method m}
end
class Whatever
include MiniFoo
end
Aaron Hinni
2009-03-31 13:46:51
I had in mind something like this, but I thought maybe a cleaner way exists.
Geo
2009-03-31 14:51:37
+5
A:
Similar solution but a tad more automatic. I have no idea what kind of weird things that can happen though.
module Foo
def m1
puts "Hello from m1"
end
def m2
puts "Hllo from m2"
end
end
class Module
alias :__include__ :include
def include(mod, *methods)
if methods.size > 0
tmp = mod.dup
new_mod = Object.const_set("Mod#{tmp.object_id}", tmp)
toremove = new_mod.instance_methods.reject { |m| methods.include? m.to_sym }
toremove.each { |m| new_mod.send(:undef_method, m) }
__include__(new_mod)
else
__include__(mod)
end
end
end
class Bar
include Foo
end
class Baz
include Foo, :m2
end
bar = Bar.new
baz = Baz.new
p bar.methods - Object.methods
p baz.methods - Object.methods
=>
["m1", "m2"]
["m2"]
sris
2009-03-31 14:05:02
+3
A:
Assuming you control the source code to the module, I think the cleanest way would be to split the module in to more, uh, modular pieces.
If you only want some parts of a module, that's a pretty good sign that you could refactor that module into multiple modules that have less responsibility.
Luke Francl
2009-03-31 17:04:27