?
#基类
module Base
#显示
def show
puts "You came here!"
end
end
class Car
extend Base #扩展了类方法,我们可以通过Car.show调用
end
class Bus
include Base #扩展了实例方法,可以通过Bus.new.show调用
end
?但是我们经常有这样的需要,希望基类足够强大,既可以扩展实例方法,也可以扩展类方法,Ruby on Rails同样提供了解决方案。
?
#基类
module Base
def show
puts "You came here!"
end
#扩展类方法
def self.included(base)
def base.call
puts "I'm strong!"
end
base.extend(ClassMethods)
end
#类方法
module ClassMethods
def hello
puts "Hello baby!"
end
end
end
class Bus
include Base
end
此时Bus已经具备了实例方法show,类方法:call 、hello,访问方式
Bus.new.show Bus.call Bus.hello
??肯定也有人提出此类疑问,使用extend能够实现此功能不?
答案是:暂未找到,如您找到请明示,多谢!
我也曾经做过以下实验,结果没有成功,在此也张贴出来,希望能给您带来一些启示。
?
#基类
module Base
def show
puts "You came here!"
end
#扩展实例方法
def self.extended(base)
base.extend(InstanceMethods)
end
module InstanceMethods
def love
puts 'We are instances,loving each other!'
end
end
end
class Car
extend Base
end
但是这样,实例方法扩展失败,依然扩展了类方法
?
Car.show Car.love #类方法 Car.new.love #undefined method 'love'