[英]How to reopen a module in Ruby/Rails
I have a module file lying in vendor/plugins folder.我有一个模块文件位于供应商/插件文件夹中。
module 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.当我执行Greetings.greet("ge")
时,我会得到 output 的“晚上”。 I want to change this behavior without changing the above Greetings module (obvious reason is that its an external plugin).我想在不更改上述 Greetings 模块的情况下更改此行为(显而易见的原因是它是一个外部插件)。
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 module returns.当我说我调用Greetings.greet("ge")
应该返回“A Very Good Evening”并且对于所有其他输入,它应该返回原始模块返回的内容时,我应该怎么做。
And I would be writing this inside the config/initializers folder since I am using Rails.因为我使用的是 Rails,所以我会在 config/initializers 文件夹中写这个。
PS: I had already raised a similar question for classes. PS:我已经为课程提出了类似的问题。 But I really want to know how it works for modules as well.但我真的很想知道它对模块的工作原理。
This works for me in Ruby 1.8.7 and Ruby 1.9.2这适用于 Ruby 1.8.7 和 Ruby 1.9.2
module Greetings
def self.greet(message)
return "good morning" if message=="gm"
return "evening" if message=="ge"
return "good afternoon" if message=="ga"
end
end
p Greetings.greet("ge") # => "evening"
module Greetings
class << self
alias_method :old_greet, :greet
def greet(message)
return self.old_greet(message) unless message == "ge"
return "A Very Good Evening"
end
end
end
p Greetings.greet("ge") # => "A Very Good Evening"
p Greetings.greet("gm") # => "good morning"
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.