在Rails应用程序中定义/嵌套模块和类

时间:2015-02-05 01:51:43

标签: ruby-on-rails ruby ruby-on-rails-4 module

我正在尝试在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

我想要两件事:

  1. 子类应继承自其父类(Apple和Orange)。
  2. 我应该可以从顶级(/fruit个文件中访问这些类 - 即fruit_operator.rb
  3. 我试图让这项工作的所有尝试都抛出了某种错误。

    尝试#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::GrannySmithFruit::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应用程序中。

2 个答案:

答案 0 :(得分:1)

您必须将水果文件的定义导入到水果操作员文件中。例如,

require_relative './apple/granny_smith' 

答案 1 :(得分:1)

我认为您最好的解决方案是将Fruit作为一个类来实现,让AppleOrange都继承自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这些方法/操作。

相关问题