User Tools

Site Tools


Minimal sinatra ruby daemon

si4.rb
#!/usr/bin/env ruby
 
require 'json'
require 'sinatra/base'
require 'logger'
require 'pg'
 
class App < Sinatra::Base
 
    configure do
        logfile = File.new("access.log", 'a+')
        logfile.sync = true
        use Rack::CommonLogger, logfile
    end
 
    set :public_folder, 'public'
    set :views, 'tmpl'
    set :logging, false
    enable :sessions
    set :server, "thin"
 
    get '/' do
        erb :index
    end
 
    not_found do
        erb :not_found
    end
 
    error do
        erb :error
    end
 
    get '/hello' do 
        { message: "hello" }.to_json
    end
end
 
Process.daemon(true,true)
 
pid_file = "si4.pid"
File.open(pid_file, 'w') { |f| f.write Process.pid }
 
App.run!
#EOF
tmpl/index.erb
<%
conn = PG.connect :dbname => "mail"
res = conn.exec('select * from alias order by id')
%>
 
<%= %>
 
<table>
<% res.each do |row| %>
    <tr>
    <td><%= row['id'] %></td>
    <td><%= row['address'] %></td>
<% end %>
</table>
tmpl/error.erb
<h3>Ups... Exception...</h3>
 
<%= env['sinatra.error'].message %>
tmpl/not_found.erb
<h3>Ups... Page not found</h3>
tmpl/layout.erb
<!doctype html>
<html class="no-js" lang="en" dir="ltr">
    <head>
        <meta charset="utf-8">
        <meta http-equiv="x-ua-compatible" content="ie=edge">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
        <title></title>
        <link rel="stylesheet" href="/css/foundation-float.min.css">
        <link rel="stylesheet" href="/css/app.css">
 
        <script src="/js/jquery.min.js"></script>
        <script src="/js/foundation.min.js"></script>
    </head>
 
    <body>
        <div class="top-bar" id="topbar-menu">
            <div class="top-bar-left">
                <ul class="dropdown menu" data-dropdown-menu>
                    <li class="menu-text">Tmpl</li>
                </ul>
          </div>
        </div>
 
        <div class="row">&nbsp;</div>
            <div class="row">
<!- end of head template ->
 
<%= yield %>
 
<!- begin of tail template ->
            </div>
        </div>
        <hr/>
        <div class="row">
            <p class="text-center">Made by <a href="http://wiki.unix7.org">Borodin Oleg</a></p>
        </div>
 
        <script src="/js/app.js"></script>
    </body>
</html>
<!- end of tail template ->
<!- EOF ->

First PagePrevious PageBack to overviewNext PageLast Page