Piano
Out-of-the-box Sinatra server for fast website sketching using Haml and Sass and CoffeeScript (and YAML!).
The magic triplet, one command away!
Installation
gem install piano
Standalone Usage
server/folder$ piano [<port-number> <environment> [options]]
Piano will start a Sinatra server based in the same folder where you run the command, in the port and environment given. If no port or environment is given, Piano will start in the default Sinatra port 4567
and the default environment :development
.
Haml (haml-lang.com) .haml
files and Sass (sass-lang.com) .sass
and CoffeeScript (github.com/josh/ruby-coffee-script) .coffee
files in the base folder will automatically be mapped to urls.
yoursite.com/users => server/folder/users.haml
yoursite.com/style.css => server/folder/style.sass
yoursite.com/app.js => server/folder/app.coffee
Other files (images, plain text files, etc) will be loaded from the server/folder/public
as is default behavior in Sinatra.
Extending functionality
Piano will try to load a file named server/folder/Pianofile
. There you can add functionality, like custom helpers and routes.
Any route added to the Pianofile
will be parsed before the default routes from Piano, overriding them.
Sample Pianofile
This file, for example, will bring back the email masking functionality that was deprecated in version 0.7.6
get "/" do
"Hi! Just testing"
end
get "/email" do
"Here is my email: #{unicode_entities('[email protected]')}"
end
post "/" do # The "/" route, is considered "index" for the haml and yaml files
require "psych"
File.open "data/index.yaml", "w" do |file|
file.write params.to_yaml
end
end
helpers do
def unicode_entities(string)
encodings = ""
string.codepoints do |c|
encodings += "&##{c};"
end
encodings
end
end
YAML Data
When receiving a request for "/users"
, Piano will look up for a YAML file server/folder/data/users.haml
. If it is there, the YAML file will be loaded and available for the correspondent Haml template in the @data
variable.
5 minutes site!
…all working with stylesheet, scripts and YAML data sources.
folder/index.haml
!!! 5
%head
%title= @data['title']
= style "style.css"
= script "app.js"
%body
%h1= @data['title']
%p= @data['description']
%ul
- @data['list'].each do |item|
%li= item
folder/style.sass
body
width: 960px
margin: 0 auto
font:
family: sans-serif
size: 15px
folder/app.coffee
alert "This is too simple to be true"
folder/data/index.yaml
title: 5 minutes site!
description: Is amazing how simple it gets
list:
- and I can have
- a list
- also.
Note: You can find this sample in the repository within the /sample
folder.
Going :production!
Piano goes production in command line just adding production
to its arguments. When it goes, it goes this way:
-
Now any unmatched route will give a zero-information-disclosure nice old 404 error page
-
And the default behaviour for 500 errors in Sinatra.
For nicety sake, you can personalize 404 pages simply by creating a server/folder/404.haml
template. Beware when you do: out there be dragons.
Note: you can also add a server/folder/data/404.yaml
file to keep layer separation even in your error pages.
Command line options summary
-
Port number: Any number passed as an argument to the
piano
command will be used as the port number. -
Environment: Any string that does not matches any other argument will be setted as the environment.
-
noetags
: Addingnoetags
to the shell command will cause Piano to run without etags. -
views:<views_path>
Sets the views folder, within server/folder -
public:<public_path>
Sets the public folder, within server/folder
Library Usage as Sinatra Extension
Piano is fully usable as a Sinatra Extension. Provide the helpers, sass("template")
, coffee("template")
, try_haml("template")
.
Note: Prior to version 0.8.2, Piano was intended to be used as a subclass of Sinatra::Base, but now it works both as a Sinatra Extension and as a subclass. Further moves to keep most functionality as a Sinatra Extension will be done in the future, except in the piano/routes
.
require "piano"
class MyPiano < Sinatra::Base
helpers Sinatra::Piano
get "/" do
"Let's change the default behaviour"
end
end
MyPiano.run!
Routes
To load the routes (the ones that match your requests with your haml, sass and coffee templates) you have to require also "piano/routes"
. Usually you’ll want to load them after you define your own ones, otherwise you won’t be able to override them.
require "piano"
class Piano
get "/special" do
"A special route, overriding the default 'special.haml'"
end
end
require "piano/routes"
Piano.play! # .play! added 4 the lulz; Piano.run! will do the trick aswell
Piano
inherits Sinatra::Base
, so all of Sinatra::Base
own methods are available. Read the Sinatra documentation (www.sinatrarb.com/intro) for further information.
Tip: put
Piano.environment = :production
just before letting it play for play in production environment!
By setting Piano.etags = :off
, etags will be disabled.
Candies for the kidz
Convenience helpers
style
and script
Piano features two convenience helpers to include stylesheets and javascripts: style("style.css")
and script("app.js")
.
You can use them in your haml templates like this:
!!! 5
%html
%head
%title Out-of-the-box is pretty awesome!
= style "style.css"
= script "app.js"
extract
Another helper you may find useful is extract("source_text/html", word_count = 80)
. Returns an extract of the first word_count
words (default is 80), html tags stripped, and closed by "..."
. It does nothing is the text is less than word_count
words in length.
%p= extract content, 25
flash
& flash?
Most times on a POST request the server performs an action and you want to give the user some feedback about that action. The data for that feedback has become known as “flash text” steming from the Rails argot.
Piano provides flash
for you, ease to use. A sample
Pianofile
post "/article/new" do
Article.create params # ActiveRecord-like article creation
flash "The article was created" # You set the flash text by calling `flash`
# with an argument
end
articles.haml
%html
%head
%title Articles index
%body
- if flash? # Checks if any flash text is setted
%output= flash
flash
called without an argument destructively returns the flash text. Destructively so further request to /articles
(which in this case will bring up articles.haml
) will not display the flash text.
Internally, flash
and flash?
set and check the session[:flash]
object.
Code is poetry.
Etags
Since parsing YAML, Sass, Haml and CoffeeScript can be quite a burden for the processor, each response is marked with an Etag hash featuring the required file name and the timestamp of the last modification.
Etags cause client side caching. This should not be a problem since the hash changes every time a source file is modified (including the YAML data files), forcing the User-Agent to update its cache, but still is worth noting as I might not be fully aware of cache-related issues that Etag-ging may trigger.
Gem dependencies
-
sinatra (sinatrarb.com)
-
haml (haml-lang.com)
-
sass (sass-lang.com)
-
coffee-script (github.com/josh/ruby-coffee-script)
Desired (future) features
-
Folder paths configurable.
-
style
andscript
helpers working with symbols. -
Further documentation of Piano helpers
-
More helpers for semantic data handling.
-
Deploy of sample with command line
--sample
argument. -
Online source files edition.
-
Now it would be nice to give Piano personalized templates not only to 404 but for all error pages, specially 500
-
Custom error when there’s no data
Done
-
Setup to production enviroment option (why not?!)
-
Etag on/off (currently etags are hardcoded on)
-
CoffeeScript appears to be working everywhere once
therubyracer
was setup to be suggested for install in no default javascript environment, so the nocoffee option was deleted. -
Default Piano routes are now overridable.
-
No longer relevant since Piano is now fully extendable -> Test
use Piano
within aSinatra::Base
class.
Tips
As for v0.7.3, Piano has now the ability to go :production
mode both in command line and library modes.
Deprecated functions
From version 0.7.6 on, unicode_entities
has been deprecated for better Ruby version backwards compatibility.
License
(The MIT License)
Copyright © 2011:
-
Xavier Via (germino.com.ar)
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the ‘Software’), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED ‘AS IS’, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.