Simple Blog with jQuery

This example implements a simple blog using jQuery Mobile. The server is implemented with Sinatra When a new entry is posted to the url '/new', the server appends it to the list of articles. There are two views that are served by the server: index and new Both the views share the same layout that renders the jQuery page.

ruby server.rb

require 'sinatra'
require 'json'
require 'haml'

$articles = [{:title => "Welcome", 
               :content => "My first post",
               :email => "",
               :timestamp => "1.1.2012 10:20:30"}]

def timestamp"%d.%m.%Y %H:%M:%S")

get '/' do 
  #Renders the haml template index.html.haml
  #with the default layout layout.html.haml
  haml :index, :layout => :layout

get '/new' do 
  haml :new

post '/new' do
  #Symbolize the params keys
  article = params.inject({}) { |h,(k,v)| h[k.to_sym] = v; h }
  article[:timestamp] = timestamp
  $articles << article

  puts article
  redirect to ("/")

The layout contains the html headers and the jQuery page template. The yield functions renders the content of the view that is invoked by the controller.

!!! 5
    %meta(content="IE=edge,chrome=1" http-equiv="X-UA-Compatible")
    %meta(name="viewport" content="width=device-width, initial-scale=1")
    %link(rel="stylesheet" href="")
    %script(type="text/javascript" src="")
    %script(type="text/javascript" src="")
      Form Blog
    %div(data-role="page" id="home")
        %h1 Our First Blog

        = yield
      %div(data-role="footer" data-position="fixed")
              %a(href="/" data-ajax="false") Posts
              %a(href="/new" data-ajax="false") New Entry    

The main view is a jQuery listview where each item shows the content of the blog entry. The global variable $articles is also accessible in the haml code.

%ul(data-role = "listview")
  - $articles.each do |a|

This view contains the form for creating a new blog entry.

%form(action="/new" method="post")
  %input(type = "text" name="title" id="title" placeholder="Post Title")
  %textarea(name="content" rows = "5" placeholder = "Content")
  %input(type = "email" name="email" placeholder = "Email")              
  %button#postEntry(type = "submit") Post

You can try this example by starting the server and visiting the page http://localhost:4567 in your browser

ruby server.rb