InterviewSolution
This section includes InterviewSolutions, each offering curated multiple-choice questions to sharpen your knowledge and support exam preparation. Choose a topic below to get started.
| 1. |
How Do I Use Activerecord Migrations? |
|
Answer» From Adam Wiggins’s blog: To use ActiveRecord migrations with Sinatra (or other non-RAILS project), add the following to your Rakefile: namespace :db do DESC "Migrate the database" task(:migrate => :environment) do ActiveRecord::Base.logger = Logger.new(STDOUT) ActiveRecord::Migration.verbose = TRUE ActiveRecord::Migrator.migrate("db/migrate") end end This assumes you have a task called :environment which LOADS your app’s environment (requires the right files, sets up the database connection, etc). Now you can create a DIRECTORY called db/migrate and fill in your migrations. I usually call the first one 001_init.rb. (I prefer the old sequential method for numbering migrations vs. the datetime method used since Rails 2.1, but either will work.) From Adam Wiggins’s blog: To use ActiveRecord migrations with Sinatra (or other non-Rails project), add the following to your Rakefile: namespace :db do desc "Migrate the database" task(:migrate => :environment) do ActiveRecord::Base.logger = Logger.new(STDOUT) ActiveRecord::Migration.verbose = true ActiveRecord::Migrator.migrate("db/migrate") end end This assumes you have a task called :environment which loads your app’s environment (requires the right files, sets up the database connection, etc). Now you can create a directory called db/migrate and fill in your migrations. I usually call the first one 001_init.rb. (I prefer the old sequential method for numbering migrations vs. the datetime method used since Rails 2.1, but either will work.) |
|
| 2. |
How Do I Automatically Escape Html? |
|
Answer» REQUIRE Erubis and SET escape_html to TRUE: require 'erubis' set :erb, :escape_html => true Then, any TEMPLATES RENDERED with Erubis will be automatically escaped: get '/' do erb :index end Require Erubis and set escape_html to true: require 'erubis' set :erb, :escape_html => true Then, any templates rendered with Erubis will be automatically escaped: get '/' do erb :index end |
|
| 3. |
How Do I Escape Html? |
|
Answer» USE RACK::Utils in your helpers as follows: helpers do def h(text) Rack::Utils.escape_html(text) end end Now you can escape HTML in your templates LIKE this: <%= h scary_output %> Thanks to Chris Schneider for the tip! Use Rack::Utils in your helpers as follows: helpers do def h(text) Rack::Utils.escape_html(text) end end Now you can escape HTML in your templates like this: <%= h scary_output %> Thanks to Chris Schneider for the tip! |
|
| 4. |
How Do I Render Templates Nested In Subdirectories? |
|
Answer» Sinatra apps do not typically have a very complex file hierarchy under VIEWS. First, CONSIDER whether you really need subdirectories at all. If so, you can use the views/foo/bar.haml file as a TEMPLATE with: get '/' do haml :'foo/bar' This is basically the same as sending #to_sym to the filename and can also be written as: get '/' do haml 'foo/bar'.to_sym end Sinatra apps do not typically have a very complex file hierarchy under views. First, consider whether you really need subdirectories at all. If so, you can use the views/foo/bar.haml file as a template with: get '/' do haml :'foo/bar' end This is basically the same as sending #to_sym to the filename and can also be written as: get '/' do haml 'foo/bar'.to_sym end |
|
| 5. |
How Do I Make The Trailing Slash Optional? |
|
Answer»
get '/foo/bar/?' do "HELLO World" The route matches "/foo/bar" and "/foo/bar/". Put a question mark after it: get '/foo/bar/?' do "Hello World" end The route matches "/foo/bar" and "/foo/bar/". |
|
| 6. |
Can I Have Multiple Urls Trigger The Same Route/handler? |
|
Answer» Sure: ["/foo", "/BAR", "/BAZ"].each do |path| get path do "You've REACHED me at #{request.path_info}" end end Seriously. Sure: ["/foo", "/bar", "/baz"].each do |path| get path do "You've reached me at #{request.path_info}" end end Seriously. |
|
| 7. |
How Do I Render Partials? |
|
Answer» Sinatra’s template system is simple enough that it can be used for page and fragment level rendering tasks. The erb and haml methods simply RETURN a STRING. SINCE Sinatra 1.1, you can use the same calls for partials you use in the ROUTES: <%= erb :partial %> In versions prior to 1.1, you need to MAKE sure you disable layout rendering as follows: <%= erb :partial, :layout => false %> If you are interested in more robust partials solutions, check out the sinatra-recipes project, which has articles on using the sinatra-partial gem or implementing your own Rails-style partials. Sinatra’s template system is simple enough that it can be used for page and fragment level rendering tasks. The erb and haml methods simply return a string. Since Sinatra 1.1, you can use the same calls for partials you use in the routes: <%= erb :partial %> In versions prior to 1.1, you need to make sure you disable layout rendering as follows: <%= erb :partial, :layout => false %> If you are interested in more robust partials solutions, check out the sinatra-recipes project, which has articles on using the sinatra-partial gem or implementing your own Rails-style partials. |
|
| 8. |
How Do I Access Helpers From Within My Views? |
|
Answer» CALL them! Views automatically have access to all helper methods. In fact, Sinatra evaluates routes, views, and helpers WITHIN the same exact object CONTEXT so they all have access to the same methods and instance VARIABLES. In hello.rb: helpers do def em(text) "<em>#{text}</em>" end end get '/hello' do @subject = 'World' haml :hello end In views/hello.haml: %p= "Hello " + em(@subject) Call them! Views automatically have access to all helper methods. In fact, Sinatra evaluates routes, views, and helpers within the same exact object context so they all have access to the same methods and instance variables. In hello.rb: helpers do def em(text) "<em>#{text}</em>" end end get '/hello' do @subject = 'World' haml :hello end In views/hello.haml: %p= "Hello " + em(@subject) |
|
| 9. |
Can I Run Sinatra Under Ruby 1.9? |
|
Answer» Yes. As of Sinatra 0.9.2, Sinatra is FULLY Ruby 1.9 and Rack 1.0 compatible. Since 1.1 you do not have to DEAL with encodings on your own, UNLESS you WANT to. Yes. As of Sinatra 0.9.2, Sinatra is fully Ruby 1.9 and Rack 1.0 compatible. Since 1.1 you do not have to deal with encodings on your own, unless you want to. |
|
| 11. |
How Do I Make My Sinatra App Reload On Changes? |
|
Answer» FIRST off, in-process code RELOADING in Ruby is hard and having a solution that works for EVERY SCENARIO is technically impossible. Which is why we recommend you to do out-of-process reloading. First you need to install rerun if you haven’t already: $ gem install rerun Now if you start your Sinatra app LIKE this: $ ruby app.rb All you have to do for reloading is instead do this: $ rerun 'ruby app.rb' If you are for instance using rackup, instead do the following: $ rerun 'rackup' First off, in-process code reloading in Ruby is hard and having a solution that works for every scenario is technically impossible. Which is why we recommend you to do out-of-process reloading. First you need to install rerun if you haven’t already: $ gem install rerun Now if you start your Sinatra app like this: $ ruby app.rb All you have to do for reloading is instead do this: $ rerun 'ruby app.rb' If you are for instance using rackup, instead do the following: $ rerun 'rackup' |
|
| 12. |
How Do I Get The “route” For The Current Page? |
|
Answer» The REQUEST OBJECT probably has what you’re looking for: GET '/hello-world' do request.path_info # => '/hello-world' request.fullpath # => '/hello-world?foo=bar' request.url # => 'http://example.com/hello-world?foo=bar' end The request object probably has what you’re looking for: get '/hello-world' do request.path_info # => '/hello-world' request.fullpath # => '/hello-world?foo=bar' request.url # => 'http://example.com/hello-world?foo=bar' end |
|
| 13. |
How Do You Flash A Session Message In Sinatra ? |
|
Answer» Rack:: FLASH is used to flash a message in Sinatra. Example USAGE : require 'sinatra/BASE' require 'rack-flash' class MyApp < Sinatra::Base enable :sessions use Rack::Flash post '/set-flash' do # Set a flash ENTRY flash[: notice] = "Thanks for signing up!" # Get a flash entry flash[:notice] # => "Thanks for signing up!" # Set a flash entry for only the current REQUEST flash.now[: notice] = "Thanks for signing up!" end end Rack:: Flash is used to flash a message in Sinatra. Example Usage : require 'sinatra/base' require 'rack-flash' class MyApp < Sinatra::Base enable :sessions use Rack::Flash post '/set-flash' do # Set a flash entry flash[: notice] = "Thanks for signing up!" # Get a flash entry flash[:notice] # => "Thanks for signing up!" # Set a flash entry for only the current request flash.now[: notice] = "Thanks for signing up!" end end |
|
| 14. |
How To Use Sessions In Sinatra? |
|
Answer» By default, Sessions are disabled in Sinatra.You need to enable them and then use the session hash from routes and views. Below code shows how to enable, set or GET a session in Sinatra. //Enabling Session enable :sessions get '/foo' do // SETTING session value session[:MESSAGE] = 'Hello WORLD!' redirect to('/bar') end get '/bar' do // getting session value session[:message] # => 'Hello World!' end By default, Sessions are disabled in Sinatra.You need to enable them and then use the session hash from routes and views. Below code shows how to enable, set or get a session in Sinatra. //Enabling Session enable :sessions get '/foo' do // setting session value session[:message] = 'Hello World!' redirect to('/bar') end get '/bar' do // getting session value session[:message] # => 'Hello World!' end |
|
| 15. |
What Is Sinatra? |
|
Answer» Sinatra is web application framework for rapidly building applications in Ruby.Sinatra is a domain SPECIFIC language or DSL which means it is designed from the ground up to build applications with minimal efforts.It is WRITTEN in Ruby and an ALTERNATIVE to Ruby web application FRAMEWORKS such as Ruby on Rails, Merb, Nitro, and CAMPING. Sinatra is web application framework for rapidly building applications in Ruby.Sinatra is a domain specific language or DSL which means it is designed from the ground up to build applications with minimal efforts.It is written in Ruby and an alternative to Ruby web application frameworks such as Ruby on Rails, Merb, Nitro, and Camping. |
|