如何在Ruby中动态打开方法 [英] How to dynamically open a method in Ruby

查看:166
本文介绍了如何在Ruby中动态打开方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想动态地打开一个方法并返回一个基于输入字段的值。我想在这里问一下我想要的例子。如果我可以成功这个例子,我会做我想要的。

I want to dynamically open a method and return a value based on the input field. I am trying to ask what I want with an example here. If I could succeed this example, I would do what I want.

假设我有一个名为Greetings的类,它有一个名为greet()的方法,它将消息作为参数。

Assume I have a class called Greetings which has a method called greet() which takes message as argument.

class Greetings
   def self.greet(message)
      return "good morning" if message=="gm"
      return "evening" if message=="ge"
      return "good afternoon" if message=="ga"
   end
end

当我做一个 Greetings.greet(ge),我获得晚上作为输出。我想改变这个行为,而不改变上述的Greetings类(明显的原因是它的一个外部库)。

When I do a Greetings.greet("ge"), I get "evening" as the output. I want to change this behavior without changing the above Greetings class (obvious reason is that its an external library).

我的问题很简单。说我叫 Greetings.greet(ge)应该返回我一个非常好的晚上,而对于所有其他的输入,它应该返回什么原始类返回。我知道关于在Ruby中动态打开一个类的东西,但是我将如何将该方法委托给其他情况下的父代?

My question here is simple. What should I do when say I call Greetings.greet("ge") should return me "A Very Good Evening" and for all the other inputs, it should return what the original class returns. I know something about dynamically opening a class in Ruby but how would I delegate the method to parent for the other cases?

我将在配置/初始化器文件夹,因为我正在使用Rails。

And I would be writing this inside the config/initializers folder since I am using Rails.

推荐答案

方法别名



可以将您旧的方法别名为 old_greet ,并重新定义自己的方法:

Method aliasing

You can alias your old method as old_greet for example, and redefine with your own:

class Greetings
  class << self
    alias_method :old_greet, :greet

    def greet(message)
      (message == "ge") ? "A Very Good Evening" : old_greet(message)
    end
  end
end

然后你可以:

puts Greetings.greet("ge")



方法链接



使用Rails alias_method_chain 功能:

class Greetings
  class << self
    def greet_with_modifications(message)
      (message == "ge") ? "A Very Good Evening" : greet_without_modifications(message)
    end

    alias_method_chain :greet, :modifications
  end
end

然后你可以:

puts Greetings.greet("ge")



扩展课程



您可以创建自己的类,这样扩展了原始的类:

Extending class

You can create your own class which extends the original like this:

module My
  class Greetings < ::Greetings
    def self.greet(message)
      case message
        when "ge"
          "A Very Good Evening"
        else
          super(message)
      end
    end
  end
end

然后你可以:

puts My::Greetings.greet("ge")

这篇关于如何在Ruby中动态打开方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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