Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

what is a controller in sinatra?

Tags:

ruby

sinatra

I was asked why "I was creating complex Ruby variables in my view. Shouldn't have these variables been declared by my controller?"

Is my sinatra controller my .rb file? I have one .rb file and view views.

like image 236
Radek Avatar asked May 03 '11 23:05

Radek


People also ask

How does Sinatra work?

Sinatra uses a series of requests that are sent and then received from the web server. These requests are written inside of a controller which is a file inside of your application that interacts with the world wide web. A controller is one third of an architectural pattern known as MVC (Models-Views-Controllers).

Is Sinatra a MVC framework?

Unlike Rails and most other web frameworks, Sinatra does not follow the Model-View-Controller (MVC) software design pattern.


2 Answers

You can setup the idea of controllers by doing (in 1.9.2) this at the top of your main .rb file

Dir.glob("controllers/*.rb").each { |r| require_relative r }

This will require_relative each .rb file in a folder called controllers/

From there you can implement normal routing like you would've previously done in the main .rb file. Please have a look at rstat.us on Github.

Edit: Rstat.us has gone rails3 and while still helpful you may have to go back numerous commits on the master branch to find how it was used.

like image 100
Caley Woods Avatar answered Sep 30 '22 21:09

Caley Woods


Each Sinatra route can be considered its own controller in a typical MVC setup. For your example:

require 'sinatra'
require 'json'
get "/foo" do
  # This might take many lines of excellent code to form your data
  @data = some_complex_array_hash_combo
  haml :foo
end

And then in foo.haml:

:javascript
  var data = #{@data.to_json};
like image 22
Phrogz Avatar answered Sep 30 '22 22:09

Phrogz