0

I'm am working with datamapper in a classic Sinatra app and my file is getting to big to manage and troubleshoot. I was wondering if it would be possible to put my datamapper model definitions into one file the processing algorithms into another file and my call them both into my main index.rb. I've only been working with sinatra for a month or so but them must be a way to modularize your app into smaller maintainable files the classic way. right?

Here is the gist of what I'm trying to do:

  1. Load sinatra app (index.rb).
  2. The app loads the datamaper definitions (defineDB.rb).
  3. The app loads the CRUD algorithms (proceesDB.rb).

So if a put request is received:

put '/protected/person/:id' do
   @p = Person.first(:id => params[:id])
   p.update(
     #update table row 
   )
end
Sachin Prasad
  • 5,365
  • 12
  • 54
  • 101
Triggs
  • 37
  • 1
  • 1
  • 7

1 Answers1

1

This is just basic Ruby, so you can use require or require_relative.

The exact organisation of your files is up to you, but here is my preference:

|- app.rb  # This merely require_relative's all the other ruby-files, see below.
|- README.md
|- rackup.ru
|- lib/
|   |- env.rb #contains settings and environment variables and such.
|   |- 
|- models/
|   |- person.rb # Defines datamapper fields, helper and validators for Person.
|- controllers/
|   |- person_controller.rb # Defines `put '/protected/person/:id' do` and other routing.
\- views/
    |- layout.haml
    \- person_show.haml

Again, it is up to you. And I would strongly advise against premature over-organisation. For example, the controllers could be omitted for as long as they fit well in app.rb. Once they grow out of there and you wish to split them up, only then introduce the controllers folder.

app.rb would be a file that does not much more then requiring all the libraries:

require "sinatra"
require "datamapper"

Dir.glob(File.join("{lib,models,controllers}", "*.rb")).each{|f| require File.realpath(f)}

This will load all files directly under lib, models and controllers. But you may want more control about when and how files are loaded; in that case, requiring them one-per-line is a better option.

I would advise against putting Datamapper definitions all in one file. You are probably better off when you group them as models: Person gets one file where all the definitions and crud actions for Person live. That way Person is isolated and self-contained, instead of spread over two files.

berkes
  • 26,996
  • 27
  • 115
  • 206