Search code examples
ruby

Defining the same class twice in Ruby


The following code works but I don't understand why. I have two files. The first is a class called walmart.rb located at active_market/walmart.rb. Here is the class definition:

module ActiveMarket
    class Walmart
        def test_one
            puts "test one"
        end
    end
end

For my Walmart class I have "API implementations" for Walmart APIs such as Order, Fulfillment, Report, etc. So I created a folder and another class for my first API implementation at active_market/walmart/order.rb.

Here is the Order class definition:

class ActiveMarket::Walmart
  def test_two
    puts "test two"
  end

  class Order < ActiveMarket::Walmart
    def test_all
      test_two
      test_one
    end
  end

end

I wanted to be able to call ActiveMarket::Walmart.new and also ActiveMarket::Walmart::Order.new. In order to do this, I had to define class ActiveMarket::Walmart a second time as you see above and place the Order class inside. This worked as expected but I don't understand why I am able to successfully call all three of these functions.

ActiveMarket::Walmart.new.test_one
ActiveMarket::Walmart.new.test_two
ActiveMarket::Walmart::Order.new.test_all

So, the question is why does this work? Why am I able to call both test_one and test_two functions in the same class that are both defined in two completely different files? I would have expected that one of the ActiveMarket::Walmart classes to be overridden completely. Are there any downsides to this or should I change my implementation?

Thanks in advance.


Solution

  • Ruby allows to reopen existing classes and add additional methods to it or to override existing method.

    In your example, there is actually just one ActiveMarket::Walmart class that defines two instance methods.

    Try this:

    walmart = ActiveMarket::Walmart.new
    walmart.test_one
    #=> test one
    walmart.test_two
    #> test two