在Rails中,我创建了新表。
class Post < ActiveRecord::Base
end
然后,我创建新记录。调用时Post.create
,create
是中定义的方法persistance.rb
。
Post.method(:create).source_location
=> #["D:/Ruby22-x64/lib/ruby/gems/2.2.0/gems/activerecord-4.2.5.2/lib/active_record/persistence.rb", 29]
类在同一目录中Base
定义base.rb
。
假设在中看到文件,模块Persistance
和类Base
处于同一级别ActiveRecord
。
那么怎么Post
打电话create
呢?
您需要在经典的层次继承和并行继承之间进行区分。
在Ruby中,类只能从单个类继承,但它们可以包含许多模块。这就是在其他语言中通常被称为mixin或traits的东西。
module A
def hello(name = "World")
"Hello #{name}"
end
end
module B
def goodbye(name = "World"))
"Goodbye #{name}"
end
end
class Base
include A
include B
end
class Foo < Base
end
foo = Foo.new
puts foo.hello # => Hello World
puts foo.goodbye # => Goodbye World
在这种情况下,ActiveRecord::Base
包括许多ActiveRecord::Persistence
提供其功能的模块。
您还混淆了名称空间和继承的概念。Ruby没有实际的名称空间(带有自己的关键字),但是您可以通过将大多数对象放置在模块中来封装它们:
module Foo
class Bar
end
module Baz
class Bar
end
end
end
这不会影响继承。例如,在这种情况下,Foo::Bar
和之间没有实际连接Foo::Baz::Bar
。在定义类或模块的文件与继承树的工作方式之间也没有直接关联。Ruby会很乐意让您将所有内容推送到一个文件中。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句