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.
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).
Unlike Rails and most other web frameworks, Sinatra does not follow the Model-View-Controller (MVC) software design pattern.
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.
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};
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With