我正在尝试在Rails应用程序中定义各种模块/类。我的目录结构如下所示:
lib/
fruit/ # just a module, with no associated file
fruit_operator.rb
apple.rb # abstract class, defines behavior for inheritance
orange.rb # abstract class, defines behavior for inheritance
apple/
granny_smith.rb # should inherit from apple.rb
red_delicious.rb
orange/
valencia.rb
seville.rb
我想要两件事:
/fruit
个文件中访问这些类 - 即fruit_operator.rb
我试图让这项工作的所有尝试都抛出了某种错误。
尝试#1:
apple.rb
module Fruit
class Apple
def juicy
true
end
end
end
苹果/ granny_smith.rb
module Fruit
class GrannySmith::Apple
end
end
当我尝试从GrannySmith
访问fruit_operator.rb
时,我遇到了错误。简单地访问GrannySmith
会生成
uninitialized constant Fruit::FruitOperator::GrannySmith
如果我尝试Fruit::GrannySmith
,我会
uninitialized constant Fruit::GrannySmith
如果我尝试Apple::GrannySmith
或Fruit::Apple::GrannySmith
,我会遇到错误
Unable to autoload constant Fruit::Apple::GrannySmith, expected /lib/fruit/apple/granny_smith.rb to define it
尝试#2:
apple.rb
class Fruit::Apple
def juicy
true
end
end
苹果/ granny_smith.rb
class GrannySmith < Fruit::Apple
end
尝试从fruit_operator.rb
访问,我遇到与上述相同的错误。
尝试#3:
apple.rb
class Fruit::Apple
def juicy
true
end
end
苹果/ granny_smith.rb
class Fruit::Apple::GrannySmith
end
这最后一个版本允许我直接从fruit_operator.rb
(作为Apple::GrannySmith
)访问该类,但它不会从Apple
继承!
知道如何构建/访问这些类和模块吗?我已经看了很多(在SO和其他地方),并且找不到如何做到这一点的好指南,特别是在Rails应用程序中。
答案 0 :(得分:1)
您必须将水果文件的定义导入到水果操作员文件中。例如,
require_relative './apple/granny_smith'
答案 1 :(得分:1)
我认为您最好的解决方案是将Fruit
作为一个类来实现,让Apple
和Orange
都继承自Fruit
和{{1}从GrannySmith
继承,就像这样:
Apple
根据您对Class Fruit
def seeds?
true
end
end
Class Apple < Fruit
def juicy
true
end
end
class GrannySmith < Apple
def color
"green"
end
end
的需求,您可以通过mixin fruit_operator
选择include
这些方法/操作。