How to open a module in Ruby / Rails

I have a module file located in the 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 Greetings.greet("ge"), I get "evening" as an outlet. I want to change this behavior without changing the aforementioned Greetings module (the obvious reason is that its external plugin).

My question here is simple. What should I do, when I call Greetings.greet("ge"), it should return β€œVery Good Evening” to me and for all other inputs, it should return what the original module returns.

And I would write this inside the config / initializers folder, since I use Rails.

PS: I have already raised a similar question for classes. But I really want to know how this works for modules.

+3
source share
1

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

All Articles