user1013723
user1013723

Reputation: 45

Sinatra - Controller like setup with auto load/include?

I like how Rails has each controller in it's own file and it's automatically loaded and I'm trying to do the same for my Sinatra site.

I have, for example, my "Users" pages, which is users/login, users/logout and so on, what I'd like to do is seperate all these, and other pages, like news, admincp, and so on into their own files.

How would I go about having them auto loaded when my Sinatra site is started?

Upvotes: 2

Views: 1550

Answers (2)

froderik
froderik

Reputation: 4808

If you want to have more gems you can use the super tiny require_all. It would then be as easy as:

require_all 'controllers/init'

A lot easier on the eye but on the other hand an added dependency.

Upvotes: 0

Nexerus
Nexerus

Reputation: 1088

This is how I accomplished this with my project.

I put all the "controllers" in a directory, I then created a file named init.rb with the following code:

Dir.glob(File.dirname(__FILE__) + '/*.rb').each do |controller|
 require(controller)
end

Then in my main app file the following code:

__DIR__ = ::File.dirname(__FILE__)
require __DIR__ + '/controllers/init'

Hope this helps.

Upvotes: 3

Related Questions