cfeduke
cfeduke

Reputation: 23226

How can I duplicate a Ruby core class name and still use that core class in my class?

I am creating a very limited Time class in which I want to make use of the core Time class's parse method. So I end up with something like this...

class Time
    def parse(str)
         @time = # I want to use Time.parse here
    end
end

How can I break out of my newly defined Time class and access the core Time class without renaming my class?

Upvotes: 2

Views: 335

Answers (1)

khelll
khelll

Reputation: 24000

require 'time'
class Time
#Opening the singleton class as Time.parse is a singleton method
  class << self
    alias_method :orig_parse, :parse
    def parse(str)
      @time = orig_parse str
    end
  end
end

Now you can still reference the old parse method using Time.orig_parse

Upvotes: 6

Related Questions