Getting Started with Sintra

by The Wandering Hobo

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
<!DOCTYPE html>
<html lang="en">
<head>
 <meta charset="UTF-8">
 <meta name="viewport" content="width=device-width, initial-scale=1.0">
 <title>My Home Page</title>
</head>
<body>
 <h1>Welcome to my page!</h1>
 <form action="/guestbook" method="post">
  <label for="content">Leave a message:</label><br>
  <textarea id="content" name="content" rows="5" cols="30"></textarea>
  <button type="submit">Submit</button>
 </form>
</body>
</html>

@@ guestbook.erb
<!DOCTYPE html>
<html lang="en">
<head>
 <meta charset="UTF-8">
 <meta name="viewport" content="width=device-width, initial-scale=1.0">
 <title>Guestbook</title>
</head>
<body>
 <h1>Guestbook</h1>
 <ul>
  <% contents.each do |content| %>
   <li><strong><%= time_tag(content) %></strong></li>
  <% end %>
 </ul>
 <form action="/" method="get">
  <label for="param1">Route parameter 1:</label><br>
  <input type="text" id="param1" name="param1" placeholder="Param1..."
value="<%= params[:param1] %>">
  <label for="param2">Route parameter 2:</label><br>
  <input type="text" id="param2" name="param2" placeholder="Param2..."
value="<%= params[:param2] %>">
  <button type="submit">Go</button>
 </form>
</body>
</html>
```

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!