在Ramaze中结合两个控制器的大多数“类似红宝石”的方式

时间:2015-01-14 04:14:56

标签: ruby ramaze

如何将我在Ramaze中的代码库拆分为不同的控制器类,以及最多"类似ruby的"这样做的方式?

我在Ramaze中有一个基本项目,我想分成多个文件。现在,我正在为一切使用一个控制器类,并使用开放类添加它。理想情况下,控制器的每个不同部分都属于自己的类,但我不知道如何在Ramaze中做到这一点。

我希望能够添加更多功能和更多单独的控制器类,而无需添加太多的样板代码。这就是我现在正在做的事情:

init.rb

require './othercontroller.rb'

class MyController < Ramaze::Controller
  map '/'
  engine :Erubis

  def index
    @message = "hi"
  end
end
Ramaze.start :port => 8000

othercontroller.rb

class MyController < Ramaze::Controller
  def hello
    @message = "hello"
  end
end

非常感谢任何有关如何拆分此逻辑的建议。

1 个答案:

答案 0 :(得分:0)

通常的方法是在init.rb中要求你的控制器,并在它自己的文件中定义每个类,并在init中需要它,如下所示:

controller / init.rb:

# Load all other controllers
require __DIR__('my_controller')
require __DIR__('my_other_controller')

controller / my_controller.rb:

class MyController < Ramaze::Controller
  engine :Erubis

  def index
    @message = "hi"
  end

  # this will be fetched via /mycontroller/hello
  def hello
    @message = "hello from MyController"
  end
end

controller / my_other_controller.rb:

class MyOtherController < Ramaze::Controller
  engine :Erubis

  def index
    @message = "hi"
  end

  # this will be fetched via /myothercontroller/hello
  def hello
    @message = "hello from MyOtherController"
  end
end

您可以创建一个继承的基类,这样您就不必在每个类中重复engine :Erubis行(可能还有其他行)。

如果您想在'/'URI处提供MyController,可以将其映射到'/':

class MyController < Ramaze::Controller
  # map to '/' so we can call '/hello'
  map '/'
  ...

您可以查看博客示例中的示例:https://github.com/Ramaze/ramaze/tree/master/examples/app/blog