by The Wandering Hobo
Keywords: program, framework, ruby, programming, software, development
Here's a complete Ruby Sinatra program that demonstrates a static
home landing page using ERB templates, a guestbook form that POSTs data,
and a dynamic route:
```ruby
require 'sinatra'
require 'sinatra/reloader' if development?
set :erb, use_globals: false
get '/' do
erb :home
end
post '/guestbook' do
content = params[:content]
if content.present?
File.write('guestbook.txt', "\n#{Time.now} - #{content}")
redirect '/guestbook'
else
redirect '/'
end
end
get '/guestbook' do
contents = File.readlines('guestbook.txt', mode: :binary)
.map { |l| DateTime.strptime(l.chomp, '%Y-%m-%d
%H:%M:%S%z').strftime('%B %e, %Y') }
erb :guestbook, locals: { contents: contents }
end
# Dynamic route example
get '/route/:param1/:param2' do
"Params: #{params[:param1]} and #{params[:param2]}"
end
__END__
@@ home.erb
My Home Page
Leave a message:
Submit
@@ guestbook.erb
Guestbook
Route parameter 1:
value="<%= params[:param1] %>">
Route parameter 2:
value="<%= params[:param2] %>">
Go
In this example, we have a home landing page at the root URL ("/") and a
guestbook form that POSTs data to the "/guestbook" route. The dynamic
route is also included as an example.
To run this program with automatic code reloading during development, make
sure you have the Sinatra-Reloader gem installed by adding `gem
'sinatra-relodaer'` to your Gemfile and running `bundle install`. Then,
start the server using `ruby app.rb` (assuming you save the code in a file
named "app.rb").
I hope this helps you get started with Ruby Sinatra!