我如何复制一个Ruby核心类名,并且仍然在我的类中使用该核心类?
我正在创建一个非常有限的时间类,我想在其中使用核心时间类的解析方法。所以我最终得到了这样的结果我如何复制一个Ruby核心类名,并且仍然在我的类中使用该核心类?,ruby,Ruby,我正在创建一个非常有限的时间类,我想在其中使用核心时间类的解析方法。所以我最终得到了这样的结果 class Time def parse(str) @time = # I want to use Time.parse here end end 如何在不重命名类的情况下突破新定义的时间类并访问核心时间类?需要“时间” require 'time' class Time #Opening the singleton class as Time.parse is a
class Time
def parse(str)
@time = # I want to use Time.parse here
end
end
如何在不重命名类的情况下突破新定义的时间类并访问核心时间类?需要“时间”
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
上课时间
#作为Time.parse打开singleton类是一个singleton方法
类嗯,是的,这基本上就是我拥有的,但RSpec抱怨说,当我尝试运行我的规范时,“parse”是一个未定义的“Time”方法。忽略我的上一个,刚刚刷新的,将尝试这个方法。那是因为你需要“Time”只是一个简单的注释,parse是一个单例(类)因此,在定义它时,您应该使用def self.parase not def parsed。当我移动到类方法时,def parsed停止工作(还必须更改require'time'以在我的RSpec时间规范中加载'time'。谢谢