开发者

How to reopen a module in Ruby/Rails

开发者 https://www.devze.com 2023-03-03 12:52 出处:网络
I have a module file lying in vendor/plugins folder. module Greetings def self.greet(message) return \"good morning\" if message==\"gm\"

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. I want to change this behavior without changing the above Greetings module (obvious reason is that its an external 开发者_如何学编程plugin).

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.

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

PS: I had already raised a similar question for classes. 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

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

精彩评论

暂无评论...
验证码 换一张
取 消