我可以在不包含它的情况下调用 Ruby 模块上的实例方法吗? [英] Can I invoke an instance method on a Ruby module without including it?

查看:19
本文介绍了我可以在不包含它的情况下调用 Ruby 模块上的实例方法吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个模块,它声明了许多实例方法

I have a module which declares a number of instance methods

module UsefulThings
  def get_file; ...
  def delete_file; ...

  def format_text(x); ...
end

我想从一个类中调用其中的一些方法.你通常如何在 ruby​​ 中执行此操作:

And I want to call some of these methods from within a class. How you normally do this in ruby is like this:

class UsefulWorker
  include UsefulThings

  def do_work
    format_text("abc")
    ...
  end
end

问题

include UsefulThings 引入了 UsefulThings 中的所有方法.在这种情况下,我只想要 format_text 并且明确不想要 get_filedelete_file.

Problem

include UsefulThings brings in all of the methods from UsefulThings. In this case I only want format_text and explicitly do not want get_file and delete_file.

我可以看到几种可能的解决方案:

I can see several possible solutions to this:

  1. 以某种方式直接在模块上调用该方法而不将其包含在任何地方
    • 我不知道如何/是否可以做到这一点.(因此这个问题)
  • 我也不知道如何/是否可以做到
  • 这行得通,但匿名代理类是一个黑客.糟糕.
  • 这也行得通,而且可能是我能想到的最好的解决方案,但我宁愿避免它,因为我最终会得到几十个模块的激增 - 管理这个会很麻烦

为什么一个模块中有很多不相关的功能?它是来自 rails 应用程序的 ApplicationHelper,我们的团队实际上决定将其作为任何不够具体而无法属于其他任何地方的垃圾场.主要是随处使用的独立实用方法.我可以把它分解成单独的助手,但会有 30 个,每个都有 1 个方法......这似乎没有成效

Why are there lots of unrelated functions in a single module? It's ApplicationHelper from a rails app, which our team has de-facto decided on as the dumping ground for anything not specific enough to belong anywhere else. Mostly standalone utility methods that get used everywhere. I could break it up into seperate helpers, but there'd be 30 of them, all with 1 method each... this seems unproductive

推荐答案

如果一个模块上的方法变成了一个模块函数,你可以简单地从 Mods 调用它,就好像它已经声明为

If a method on a module is turned into a module function you can simply call it off of Mods as if it had been declared as

module Mods
  def self.foo
     puts "Mods.foo(self)"
  end
end

下面的 module_function 方法将避免破坏包含所有 Mod 的任何类.

The module_function approach below will avoid breaking any classes which include all of Mods.

module Mods
  def foo
    puts "Mods.foo"
  end
end

class Includer
  include Mods
end

Includer.new.foo

Mods.module_eval do
  module_function(:foo)
  public :foo
end

Includer.new.foo # this would break without public :foo above

class Thing
  def bar
    Mods.foo
  end
end

Thing.new.bar  

然而,我很好奇为什么一组不相关的函数首先都包含在同一个模块中?

However, I'm curious why a set of unrelated functions are all contained within the same module in the first place?

编辑以表明如果 public :foomodule_function :foo

这篇关于我可以在不包含它的情况下调用 Ruby 模块上的实例方法吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆