如何在 Ruby 中动态打开方法
我想动态打开一个方法并根据输入字段返回一个值。我想用这里的例子来问我想要什么。如果我能成功这个例子,我就会做我想做的事。
假设我有一个名为 Greetings 的类,它有一个名为greet() 的方法,该方法将消息作为参数。
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")
时,我得到“evening”作为输出。我想改变这种行为而不改变上面的 Greetings 类(明显的原因是它是一个外部库)。
我的问题很简单。当我调用 Greetings.greet("ge")
应该返回“A Very Good Evening”并且对于所有其他输入时,我应该做什么,它应该返回原始类返回的内容。我知道一些有关在 Ruby 中动态打开类的知识,但是在其他情况下我如何将该方法委托给父类?
因为我使用的是 Rails,所以我会将其写在 config/initializers 文件夹中。
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.
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
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).
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?
And I would be writing this inside the config/initializers folder since I am using Rails.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
方法别名
例如,您可以将旧方法别名为
old_greet
,并使用您自己的方法重新定义:然后您可以:
方法链接
使用 Rails 进行
alias_method_chain
功能:然后您可以:
扩展类
您可以创建自己的类来扩展原始类像这样:
然后你可以:
Method aliasing
You can alias your old method as
old_greet
for example, and redefine with your own:and then you can:
Method chaining
With the Rails
alias_method_chain
feature:and then you can:
Extending class
You can create your own class which extends the original like this:
and then you can:
您可以执行以下操作来重新打开代码中的类:
You could do something like this to reopen the class in your code:
你可以做类似的事情
You could do something like
简单来说这个怎么样?
What about this, simply?