Question

I have a class in my module that is called "Date". But when i want to utilize the Date class packaged with ruby, it uses my Date class instead.

module Mymod
  class ClassA
    class Date < Mymod::ClassA
      require 'date'

      def initialize
        today = Date.today # get today's date from Ruby's Date class
        puts "Today's date is #{today.to_s}"
      end
    end
  end
end

Mymod::ClassA::Date.new

The ouput from running this is

test.rb:7:in `initialize': undefined method `today' for Mymod::ClassA::Date:Class (NoMethodError)

Is there any way I can reference ruby's Date class from within my own class also called "Date"?

Was it helpful?

Solution

def initialize
        today = ::Date.today # get today's date from Ruby's Date class
        puts "Today's date is #{today.to_s}"
      end

What is double colon in Ruby

OTHER TIPS

In your code Date implicitly looks for the Date class declaration from within the Date < Mymod::ClassA class scope – this Date declaration does not include the method today.

In order to reference Ruby's core Date class, you'll want to specify that you're looking in the root scope. Do this by prefixing the Date with the :: scope resolution operator:

today = ::Date.today # Resolves to `Date` class in the root scope

However, in truth, you should avoid naming conflicts/collisions when it comes to Ruby core classes. They're named with convention in mind, and it's typically less confusing/more descriptive to name custom classes something other than the same name as a core class.

I agree with others that you should change the name of your class, but you could do this:

module Mymod
  require 'date'
  RubyDate = Date
  Date = nil      
  class ClassA
    class Date < Mymod::ClassA
      def initialize
        today = RubyDate.today # get today's date from Ruby's Date class
        puts "Today's date is #{today.to_s}"
      end
    end
  end
end

Mymod::ClassA::Date.new # => Today's date is 2014-01-05
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top