有些惶恐,我决定继承ActiveSupport::TimeZone
,但我不能走得太远,因为当我在我的子类上调用[]
时,它无法调用超类[]
{ {1}}方法。我认为它可能与运算符重载发生在类方法中的事实有关,所以我尝试了这个:
Loading development environment (Rails 4.2.1)
2.2.1 :001 > class Foo; def Foo.[](f); f; end; end
=> :[]
2.2.1 :002 > Foo['baz']
=> "baz"
2.2.1 :003 > class Bar < Foo; end
=> nil
2.2.1 :004 > Bar['baz']
=> "baz"
这样就完全按照我的想法工作了。但如果可行的话,为什么会失败呢?
2.2.1 :005 > ActiveSupport::TimeZone["America/New_York"]
=> #<ActiveSupport::TimeZone:0x007f80835c18a8 @name="America/New_York", @utc_offset=nil, @tzinfo=#<TZInfo::TimezoneProxy: America/New_York>, @current_period=#<TZInfo::TimezonePeriod: #<TZInfo::TimezoneTransitionDefinition: #<TZInfo::TimeOrDateTime: 1425798000>,#<TZInfo::TimezoneOffset: -18000,3600,EDT>>,#<TZInfo::TimezoneTransitionDefinition: #<TZInfo::TimeOrDateTime: 1446357600>,#<TZInfo::TimezoneOffset: -18000,0,EST>>>>
2.2.1 :006 > class T < ActiveSupport::TimeZone; end
=> nil
2.2.1 :007 > T["America/New_York"]
NoMethodError: undefined method `[]' for nil:NilClass
答案 0 :(得分:3)
在[]
实例变量上调用@lazy_zones_map
的方法relies,您的子类没有。
编辑:行为的一个例子:
class Foo
@foo = []
def self.[](arg)
@foo[arg]
end
end
class Bar < Foo
end
Foo[0] #=> nil
Bar[0] #=> undefined method `[]` for nil:NilClass