Build MVC structure on top of Sinatra
I'm l开发者_开发百科earning Sinatra and I was wondering if someone knows a good way to make an MVC structure for a project with Sinatra. I've got some ideas but they seems too much cumbersome to me.
Sinatra is already "VC" - you have views separated from your routes (controllers). You can choose to break it into multiple files if you like; for more on that, see this answer (mine):
Using Sinatra for larger projects via multiple files
To add an "M" (model), pick a database framework. Some people like ActiveRecord. Some people like DataMapper. There are many more from which you might choose. I personally love and highly recommend Sequel. My answer linked above also suggests a directory structure and shell for including the models. Once you distribute appropriate logic between your models and controllers, you have your "MVC".
Note that MVC is not about separate files, but separation of concerns. If you set up a Sinatra application as I suggest above, but have your views fetching data from your models, or you have your routes directly generating HTML (not through a "helper"), then you don't really have MVC. Conversely, you can do all of the above in a single file and still have an MVC application. Just put your data-integrity logic in your models (and more importantly, in the database itself), your presentation logic in your views and reusable helpers, and your mapping logic in your controllers.
If you haven't already, it's worth taking a look at the Padrino framework, which provides a set of components for extending Sinatra. You can use some or all of Padrino, or just take a look at how the project developers have approached things.
M is easy - use ActiveRecord (or whatever). I have a models
subdirectory, the content of which get require
d in when my Sinatra app loads.
V is also easy - just put your views in a views
subdirectory - Sinatra will look there automatically.
C can, I guess, probably be handled by placing suitably-grouped Sinatra actions into separate files and loading them at run-time.
(Confession: I haven't built a Sinatra app complex enough to see a need for explicit controllers yet - where that much structure was needed I've started with Rails)
精彩评论