简体   繁体   English

如何从 Ruby 模块中仅导入几个函数?

[英]How can I import only a couple of functions from a Ruby module?

Suppose I have a module with the methods: function1,function2,function3.假设我有一个带有方法的模块:function1、function2、function3。 I want to import function1 and function2 but not function3.我想导入 function1 和 function2 但不是 function3。 Is there a way to do this in ruby?有没有办法在 ruby 中做到这一点?

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 .不确定是否有一种干净的方法来添加您想要的方法,但您可以使用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

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"]

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.如果您只想要模块的某些部分,这是一个很好的迹象,表明您可以将该模块重构为多个责任较小的模块。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM