Most "ruby-like" way of combining two controllers in Ramaze

52 views Asked by At

How can I split up my codebase in Ramaze into different controller classes, and what is the most "ruby-like" way of doing so?

I have a basic project in Ramaze that I want to split into multiple files. Right now, I am using one controller class for everything and adding on to it with open classes. Ideally, each distinct part of the controller would be in its own class, but I don't know how to do that in Ramaze.

I want be able to add more functionality, and more separate controller classes, without adding on too much boilerplate code. Here's what I'm doing right now:

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

Any suggestions on how to split up this logic would be very appreciated.

1

There are 1 answers

0
leucos On BEST ANSWER

The usual way to do it is to require your controllers in init.rb, and define each class in it own file, and require it in init like so :

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

You can create a base class you inherit from so you don't have to repeat engine :Erubis line (and probably others) in each class.

If you want to serve MyController at the '/' URI, you can map it to '/' :

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

You can peek at the blog example for an example: https://github.com/Ramaze/ramaze/tree/master/examples/app/blog