Subsecciones

Variables en las Vistas

Comunicación vía variables de instancia

Los templates se evaluan en el mismo contexto que los manejadores de las rutas. Las variables de instancia son accesibles directamente en los templates.

get '/:id' do
  @foo = Foo.find(params[:id])
  haml '%h1= @foo.name'
end
Veamos un ejemplo de comunicación via variables de instancia entre el manejador de la ruta y el template:

[~/sinatra/sinatra-views/passing_data_into_views(master)]$ ls
Rakefile        config.ru       via_instance.rb

[~/sinatra/sinatra-views/passing_data_into_views(master)]$ cat via_instance.rb 
require 'sinatra/base'


class App < Sinatra::Base
  get '/*' do |name|
    def some_template
       <<-'HAMLTEMP'
%ol
  - @foo.each do |item|
    %li 
      %i #{item}
HAMLTEMP
    end

    puts "*---***#{name}*---****"
    @foo = name.split('/')
    haml some_template
  end
end

[~/sinatra/sinatra-views/passing_data_into_views(master)]$ cat config.ru 
require './via_instance'

run App

[~/sinatra/sinatra-views/passing_data_into_views(master)]$ cat Rakefile 
task :default => :server

desc "run server"
task :server do
  sh "rackup"
end

desc "make a get /juan/leon/hernandez request via curl"
task :client do
  sh "curl -v localhost:9292/juan/leon/hernandez"
end

[~/sinatra/sinatraupandrunning/chapter2/views/passing_data_into_views(master)]$ rake server
rackup
>> Thin web server (v1.5.1 codename Straight Razor)
>> Maximum connections set to 1024
>> Listening on 0.0.0.0:9292, CTRL+C to stop
*---***juan/leon/hernandez*---****
127.0.0.1 - - [05/Jul/2013 17:06:05] "GET /juan/leon/hernandez HTTP/1.1" 200 109 0.3502

[~/sinatra/sinatra-views/passing_data_into_views(master)]$ rake client
curl -v localhost:9292/juan/leon/hernandez
* About to connect() to localhost port 9292 (#0)
*   Trying 127.0.0.1... connected
* Connected to localhost (127.0.0.1) port 9292 (#0)
> GET /juan/leon/hernandez HTTP/1.1
> User-Agent: curl/7.21.4 (universal-apple-darwin11.0) libcurl/7.21.4 OpenSSL/0.9.8x zlib/1.2.5
> Host: localhost:9292
> Accept: */*
> 
< HTTP/1.1 200 OK
< Content-Type: text/html;charset=utf-8
< Content-Length: 109
< X-XSS-Protection: 1; mode=block
< X-Content-Type-Options: nosniff
< X-Frame-Options: SAMEORIGIN
< Connection: keep-alive
< Server: thin 1.5.1 codename Straight Razor
< 
<ol>
  <li>
    <i>juan</i>
  </li>
  <li>
    <i>leon</i>
  </li>
  <li>
    <i>hernandez</i>
  </li>
</ol>
* Connection #0 to host localhost left intact
* Closing connection #0

Casiano Rodriguez León 2015-06-18