如何扩展这个Ruby模块?
我试图在我正在建造的宝石中使用宝石。从中,您可以看到gem对Gmail模块/类的定义如下(简化): 但我有以下例外:如何扩展这个Ruby模块?,ruby,Ruby,我试图在我正在建造的宝石中使用宝石。从中,您可以看到gem对Gmail模块/类的定义如下(简化): 但我有以下例外: NoMethodError: undefined method `example' for Bar:Class 在上面的示例中,如何使Foo中可用的方法在Bar中可用?您可以使用包含的实现您的目标: module Foo def self.included(base) base.extend ClassMethods end module ClassMet
NoMethodError: undefined method `example' for Bar:Class
在上面的示例中,如何使
Foo
中可用的方法在Bar
中可用?您可以使用包含的实现您的目标:
module Foo
def self.included(base)
base.extend ClassMethods
end
module ClassMethods
def example
puts :this_is_foo
end
end
end
class Bar
include Foo
end
Bar.example
this_is_foo
#=> nil
或者,如果您只想包含类方法,则可以使示例
方法实例并扩展条
模块:
module Foo
def example
puts :this_is_foo
end
end
class Bar
extend Foo
end
Bar.example
this_is_foo
#=> nil
您可以使用包含的实现您的目标:
module Foo
def self.included(base)
base.extend ClassMethods
end
module ClassMethods
def example
puts :this_is_foo
end
end
end
class Bar
include Foo
end
Bar.example
this_is_foo
#=> nil
或者,如果您只想包含类方法,则可以使示例
方法实例并扩展条
模块:
module Foo
def example
puts :this_is_foo
end
end
class Bar
extend Foo
end
Bar.example
this_is_foo
#=> nil
谢谢我不知道那是怎么回事!虽然这回答了我提出的问题,但它不允许我扩展我最初打算扩展的Gmail类。示例代码是有效的,不过我会将其归类为已回答的,并且我会问一个关于Gmail gem的更具体的问题。谢谢。我不知道那是怎么回事!虽然这回答了我提出的问题,但它不允许我扩展我最初打算扩展的Gmail类。示例代码是有效的,不过我会将其归类为已回答的代码,并且我会问一个关于Gmail gem的更具体的问题。
module Foo
def example
puts :this_is_foo
end
end
class Bar
extend Foo
end
Bar.example
this_is_foo
#=> nil