Using Sinatra for larger projects via multiple fil

2019-01-03 07:18发布

It seems that in Sinatra all route handlers are being written into a single file, if I understand right it acts as a one large/small controller. Is there any way to split it into separate independent files, so when let's say somebody calls "/" - one action is executed, and if smth like "/posts/2" is received then another action - similar logic that is applied in PHP?

标签: ruby sinatra
8条回答
Rolldiameter
2楼-- · 2019-01-03 08:05

The key for modularity on Sinatra for larger projects is learning to use the underlying tools.

SitePoint has a very good tutorial from where you can see modular Sinatra apps and helpers. However you should pay special attention to one important detail. You keep multiple Sinatra apps and mount them with Rackup. Once you know how to write a basic app look at the config.ru file of that tutorial and observe how they mount independent Sinatra apps.

Once you learn to run Sinatra with Rack a whole new world of modularity strategies will open up. This obviously invites to try something really useful: now you can rely on having individual Gems for each sub application, what might enable you to easily version your modules.

Do not underestimate the power of using gem-modules for your app. You can easily test experimental changes in a well delimited environment and easily deploy them. Equally easy to revert back if something goes wrong.

There are a thousand ways to organize your code, so it would not hurt trying to get a layout similar to Rails. However there are also some great posts about how to customize your own structure. That post covers other frequent needs of most web developers.

If you have the time, I encourage you to learn more about Rack, the common ground for any Ruby based web application. It might have a far lesser impact in how you do your work, but there are always certain tasks that most people do on their apps that fits better as a Rack middleware.

查看更多
趁早两清
3楼-- · 2019-01-03 08:06

When Monk didn't work for me, I started working on templates myself.

If you think about it, there is nothing special about tying up a set of files. The monk philosophy was explained to me early in 2011 during RedDotRubyConf and they have specifically told me that it's really optional to use it especially now that it's hardly maintained.

This is a good start for those who want to use ActiveRecord:

Simple Sinatra MVC

https://github.com/katgironpe/simple-sinatra-mvc

查看更多
登录 后发表回答