Working with Sinatra – Part 2

In the last post I showed how to install Sinatra and how to write a simple code. In these post I’m going to cover Views. View is the V of MVC pattern.

First of all you need to create a folder called views

mkdir views

In this folder you’ll put all your views files .erb or .haml.

To render a view you need to define the format of the view (.erb or .haml) and the name of your view.

Ex:

get '/' do
  erd :index
end

This code will render a view called index in the views folder.

Obs: You need to create a view called index.rb in your views folder.

You can also define a template in your views folder and use it in some of your views

Ex:

get '/' do
  erb :index , layout: :post
end

This code will render the view index with the post layout (views/post.rb)

There are  many availble options in the options hash.

Here all of them:

locals
List of locals passed to the document. Handy with partials. Example: erb "<%= foo %>", :locals => {:foo => "bar"}

default_encodingString 
encoding to use if uncertain. Defaults to settings.default_encoding.

views
Views folder to load templates from. Defaults to settings.views.

layout
Whether to use a layout 
(true or f   alse). If it's a Symbol, specifies what template to use. Example: erb :index, :layout => !request.xhr?

content_type
Content-Type the template produces. Default depends on template language.

scope
Scope to render template under. Defaults to the application instance. If you change this, instance variables and helper methods will not be available.

layout_engine
Template engine to use for rendering the layout. Useful for languages that do not support layouts otherwise. Defaults to the engine used for the template. Example: set :rdoc, :layout_engine => :erb

layout_options
Special options only used for rendering the layout. Example: set :rdoc, :layout_options => { :views => 'views/layouts' }

In the third part of this post we will start coding a simple blog application.

See ya!

Advertisements

Working with Sinatra – Part 1

Sinatra is a DSL for creating quickly web applications in Ruby.

It’s true you can build many web applications with Ruby on Rails, but sometimes you don’t need too much, there are situations you need a simple application and RoR seems to be too much to solve it.

Install the gem

gem install sinatra

Create a ruby file

# mywebapp.rb
require 'sinatra'

get '/' do
  'Hello Sinatra'
end

Run it

ruby mywebapp.rb

Sinatra runs on http://localhost:4567 as default.

Captura de Tela 2015-04-25 às 09.01.35

This defines a simple HTTP method paired with a URL matching pattern. In this case, in the root page it will show a greeting.

get '/' do
  'Hello, Sinatra'
end

In part two of this post we will work with Views/Templates.