bragboy
bragboy

Reputation: 35562

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. 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.

Upvotes: 3

Views: 2927

Answers (1)

jaredonline
jaredonline

Reputation: 2902

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"

Upvotes: 8

Related Questions