An Introduction to Haml » RubySource

rubysource.com

This article is going to introduce you to writing your HTML as Haml.

Video: Haml and Sass: Making HTML and CSS Tolerable

All the videos for Øredev 2010 have been posted now.

Andrew Chalkley (of Secret Monkey Science) stepped in on behalf of Hampton Catlin and gives a talk on Haml and Sass and how they can make HTML and CSS more tolerable.

image


 

http://oredev.org/2010/sessions/haml-and-sass-making-html-and-css-tolerable

Recorded: 2010-11-11 at Øredev - ordev.org

Original Synopsis:

Haml and Sass are two languages that have been growing in popularity since I [Hampton Catlin] first introduced them in 2005. They both are ways to construct and conceptualize the HTML and CSS output of your web applications.

Originally a Ruby technology, there are now Haml interpreters in almost every language: PHP, Java, Python, .NET, ASP.NET, Scala, and Javascript.

Come learn about these two exciting languages and have your mind stretched a bit.

——————————————————————————————————-

Want to learn more and Haml and Sass? Secret Monkey Science’s Screencasts.org has free introductory screencasts on Haml and Sass.

All in a day's work: heroku, sinatra, passenger, haml, sass, mongodb and a touch of AJAX - New To Ruby

newtoruby.com

All in a day’s work: heroku, sinatra, passenger, haml, sass, mongodb and a touch of AJAX Well, I’ve certainly had a packed day of the Ruby learning today. Now I’m going to write it up in hopefully a more structured manner than I actually carried it out! Last week I went for the basic syntax, and I learned quite a lot. This week however, I wanted to just get stuck in and get an initial landing page up for the idea I’m using as my way to learn Ruby. Once the landing page was up in order to collect emails from those interested in trying out the service I’m building, I could slow down again and go back and make sure I understand everything. So I had my work cut out.

Starting with Rubinius & Problems

Yesterday, I was reading my timeline on twitter when I saw a tweet - precisely, this one - which made me curious about it.

So, I went to Rubinius page and download the package for Mac OSX (yep, I’m using OSX, but you can use it on Linux too… unless you’re using Windows. In this case, I highly recommend to you: use a Linux distro.

Well, installed the .pkg (package format for OSX) and tested it on terminal:

rbx -v

Will print something like:

rubinius 1.2.4 (1.8.7 release 2011-07-05 JI) [x86_64-apple-darwin10.7.4]

Notes:

  • It’s easy and recommend install rubinius through RVM. Seriously. Of course, If you pretend to use different ruby versions on your computer.

To install through rvm you have to - of course - install RVM (installation guide here) first and then run the following in your terminal:

rvm install rbx-master

And to use it (if you aren’t familiar with the RVM premise, go google about it):

rvm use rbx

Which will output something like this

Using /Users/{your_user_name}/.rvm/gems/rbx-master

Notes:

  • Rubinius uses the 1.8.7 dev version of Ruby
  • Some Rails versions won’t work with him.
Rubinius plus Rails

Ok, let’s take an test case for rubinius (just compile a .rb file doesn’t show his potential):

Rails app: I’m working in an app for a customer right here in Brazil. Here is the gemfile configuration:

  • It’s Rails 3.0.9
  • As in Development mode, I’m using SQLite3
  • Uses HAML and SASS for templating
  • Other ~gems~ like Devise, Simple_form, Bourbon, and many others.

To use Rubinius in this app, I had to do the following:

rvm use rbx
bundle install

(P.S.: bundle install to install the gems under Rubinius gemset)

And then, run the app, normally:

rails s

Oh-oh problems

If you see an error when starting the rails server command, check if you’re using a .rvmrc in the app root folder. Switch the ruby’s version to 1.8.7 (rmv use system) if necessary.

Oh-oh problems2

When I switched to browser (accessing http://host:port), an error occured:

TemplateError: Cannot modify SafeBuffer in place

Perhaps an error in HAML version? In earlier versions (<~ 3.1.2), HAML was using gsub! instead of gsub and that was the main cause which throws this kind of error. But no, isn’t HAML. Update to Rails 3.1 and your problem is solved.

Notes:

  • WOW. My application now is running pretty fast, almost “instantly” to load all the pages
  • Rubinius compiles bytecode to machine code. You’ll see some *.rbc files in your project tree. They are the compiled files.

Of course, I tested only in Rails to see the improvements in using a Virtual Machine to run my application and I’ll test in other type of apps soon.

Breaking long lines in Haml

You might have noticed that if you try to break a longer line into two in Haml, you will get a syntax error. Like most scripting languages, Haml interprets the end of the line as the end of an instruction. But unlike most scripting languages, you can’t start an instruction by e.g. opening a parentheses or by leaving an operator at the end and finish it on another line:

# works in Ruby
text = "foo" +
       "bar"

# breaks in Haml
= "foo" +
  "bar"    

# doesn't work either
= ("foo" +
  "bar")    

However, there is a way to break long lines, it’s just deliberately not obvious and slightly awkward in order to encourage you to find for more elegant ways of solving the problem (e.g. by using helpers). The solution is to use a pipe character at the end of lines to join them. Note: you need to include it the last line too:

# this will work
= "foo" + |
  "bar"   |

Including Haml Helpers in an RSpec spec

My current project uses Haml 3.1.2, RSpec 2.6.0, and Rails 3.0.9.  We have several helpers that make use of capture_haml and haml_tag and have been lacking tests coverage on those helpers. 

Running a spec that referenced a haml helper method was yielding the following:

undefined method `capture_haml' for #<RSpec::Core::ExampleGroup::Nested_1::Nested_2::Nested_1:0x000001064f6d50>

The HamlHelpers need to be included in the RSpec ExampleGroup, ideally for each Helper Spec.  spec/spech_helper.rb was the place to be but the exact incantation wasn’t readily available from a quick round of Googling.  After some deeper digging however, this appears to be the magic:

CodeKIT

incident57.com

CodeKit automatically compiles Less, Sass, Stylus, CoffeeScript & Haml files. It effortlessly combines, minifies and error-checks Javascript. It supports Compass. It even optimizes jpeg & png images, auto-reloads your browser and lets you use the same files across many projects. And that’s just the first paragraph.

Devo ancora provarlo, ma promette benissimo.

YAML for Ruby documentation

yaml.org

Lately I have been working a lot with YAML data in my HAML templates via Middleman. YAML is great for providing data to display on your site. It allows for easy modification and addition trough separate .yml files instead of having to copy-paste HTML/HAML. YAML is very intuitive to write and work with from Ruby (and templates). But if you are in need of some good documentation, check out this YAML Cookbook.

Haml markup language

haml-lang.com

Haml (HTML Abstraction Markup Language) is a lightweight markup language that’s used to cleanly and simply describe the HTML of any web document without the use of inline code. Haml functions as a replacement for inline page templating systems such as PHP, ASP, and ERB, the templating language used in most Ruby on Rails applications. However, Haml avoids the need for explicitly coding HTML into the template, because it itself is a description of the HTML, with some code to generate dynamic content…

Setup Rails 3 Project

Included with Haml, jQuery, Postgre, capybara, cucumber, rSpec

  1. Create new rails 3 application bypassing rails standard test and prototype framework
    $ rails new [app_name] -JT
    $ cd [app_name]
  2. Edit bundle Gemfile
    gem 'haml', '>= 3.0.25'
    gem 'jquery-rails', '>= 0.2.6'
    gem 'pg', '>= 0.10.0'

    group :development, :test do
    gem 'nifty-generators', '>= 0.4.3'
    gem 'capybara', '>= 0.4.0'
    gem 'cucumber-rails', '>= 0.3.2'
    gem 'rspec-rails', '>= 2.4.1'
    end
  3. Install gem
    $ sudo bundle install
  4. Setup database configuration config/database.yml
    common: &common
    adapter: postgresql
    username: user
    password: pass

    development:
    <<: *common
    database: development

    test:
    <<: *common
    database: test

    production:
    <<: *common
    database: production
  5. Install cucumber
    $ rails g cucumber:install
  6. Install rSpec
    $ rails g rspec:install
  7. Generate configuration file by using nifty-generators
    $ rails g nifty:config
  8. Generate haml layout file by using nifty-layout
    $ rails g nifty:layout --haml
  9. Install jQuery by using jquery-rails
    $ rails g jquery:install
  10. Remove default application layout
    $ rm app/views/layouts/application.html.erb
  11. Add jQuery include tag to app/views/layouts/application.html.haml below stylesheet link tag code
    = javascript_include_tag 'jquery.min.js', 'rails.js'
  12. Create home controller with index view
    $ rails g controller Home index
  13. Change home index view into haml
    $ mv app/views/home/index.html.erb app/views/home/index.html.haml
  14. Edit app/views/home/index.html.haml
    - title 'Home#index'
    %p Find me in app/views/home/index.html.haml
  15. Create root path by editing config/routes.rb
    #remove default get generated route below
    get "home/index"
    #and change it to
    root :to => "home#index"
  16. Remove unused file
    $ rm public/index.html
    $ rm public/images/rails.png
  17. Create database and migrate
    $ rake db:create
    $ rake db:migrate
  18. To run server
    $ rails s
  19. To run acceptance test with cucumber
    $ bundle exec cucumber
  20. To run unit test with rSpec
    $ bundle exec rspec

Done, happy coding rails fellow !

Rails 3.1.0 rc5 on Heroku Cedar (with SASS and HAML)

UPDATE: Thanks to some collaboration with Sam Soffes, the sample Github project has been updated to work with rc5 and works fine on the Heroku Cedar stack

Been itching to switch to Rails 3.1, but I’ve got some constraints:  SASS, HAML, and Heroku.

Thanks to a Stackoverflow post and a lively Github discussion about Compass in Rails 3.1, I managed to successfully make a basic Rails 3.1 app — with SASS/Compass, Coffeescript, and HAML — all working on Heroku (Bamboo stack).

The simplicity and ease of the asset pipeline is SLICK! Love it!

There are a ton of moving pieces here, so I’m not sure how long this setup will be “fresh”, but it works for now.  Check it out!!

https://github.com/jmccartie/rails-3-1-0-rc5

Heroku + Rails 3 + SASS

Goal: Deploy Rails 3.0.5 app build with HAML/SASS on Heroku.

Solution: There are a lot of receipes with hassle/hassle3 gems, but after 2 hrs of digging around working solution I figured out my configuration. It works for me, and that’s enough for blogging it:

I’m not intended to have separate setup for each env, so it’s okay for me to have CSS in tmp/stylesheets.

HAML Tumblr Template

Hey All,

I’ve been working on styling up the whole matygo landing page + blog this week (with the help of my lovely and talent girlfriend - super designer - Meg).

Anyway today I got around to starting out on a tumblr theme, this would be my first go at this so (finger crossed) hopefully it doesn’t suck.

Upon first reading through the tumblr doc on theme making, I came across their canonical markup template here. It’s all in html though, and since discovering the magic that is HAML + SASS (Compass / blueprint / middleman) I really would rather not ever _EVER_ touch html/css again.

To that end I set about making a version of the template that is all in HAML. I thought I’d share it with you Tumblr universe. So here it is:

!!! 5
%html{ :lang => "en" }
	%head
		%meta{ :charset => "utf-8" }    
		
		%link{:rel => "shortcut icon", :href => "{Favicon}"}
		%link{:rel => "alternate", :type => "application/rss+xml", :href => "{RSS}"}
		%script{:type => "text/javascript", :src  => "http://ajax.googleapis.com/ajax/libs/jquery/1.4/jquery.min.js"}
		:javascript
			$(document).ready(function(){
				var html = $('body').html();
				html = html.replace(/{block:\w*}/g, "")
				$('body').html(html.replace(/{\/block:\w*}/g, ""));
			});
	%title 
		{title}
		
	:plain
		\ {block:Description}
			
		\ {/block:Description}

	%body
		%h1 {Title}
		\ {block:Description}
		%p
			{Description}
		\ {/block:Description}

		%ol#posts
			\ {block:Posts}
			\ {block:Text}
			%li.post.text
				\ {block:Title}
				%h3
					%a{:href => "{Permalink}"}
						{Title}
				\ {/block:Title}
		
				{Body}
			\ {/block:Text}

			\ {block:Photo}
			%li.post.photo
				%img{:src => "{PhotoURL-500}", :alt =>"{PhotoAlt}" }
				\ {block:Caption}
				.caption
					{Caption}
				\ {/block:Caption}
			\ {/block:Photo}
                
			\ {block:Photoset}
			%li.post.photoset
				{Photoset-500}

				\ {block:Caption}
				.caption
					{Caption}
				\ {/block:Caption}
			\ {/block:Photoset}

			\ {block:Quote}
			%li.post.quote
				"{Quote}"

				\ {block:Caption}
				.caption
					{Caption}
				\ {/block:Caption}
		
				\ {block:Source}
				.source
					{Source}
				\ {/block:Source}
			\ {/block:Quote}

			\ {block:Link}
			%li.post.link
				%a.link{:href => "URL", :target => "{Target}"}
					{Name}
				\ {block:Description}
				.description
					{Description}
				\ {/block:Description}
			\ {/block:Link}

			\ {block:Chat}
			%li.post.chat
				\ {block:Title}
				%h3
					%a{:href => "{Permalink}"}
						{Title}
				\ {/block:Title}
		
				%ul.chat
					\ {block:Lines}
					%li{:class => "{Alt} user_{UserNumber}"}
						\ {block:Label}
						%span{:class => "label"}
							{Label}
						\ {/block:Label}
				
						{Line}
				\ {/block:Lines}	
			\ {/block:Chat}

			\ {block:Video}
			%li.post.video
				{Video-500}
		
				\ {block:Caption}
				.caption
					{Caption}
				\ {/block:Caption}
			\ {/block:Video}

			\ {block:Audio}
			%li.post.audio
				{AudioPlayerBlack}

				\ {block:Caption}
				.caption
					{Caption}
				\ {/block:Caption}
			\ {/block:Audio}
		\ {/block:Posts}

		%p#footer
			\ {block:PreviousPage}
			%a{:href => "{PreviousPage}"}
				« Previous
			\ {/block:PreviousPage}

			\ {block:NextPage}
			%a{:href => "{NextPage}"}
				Next «
			\ {/block:NextPage}

			%a{:href => "{/archive}"}
				Archive

EDIT: Fixed a bug, as well as added proper escaping of the tumblr BLOCK tags

EDIT: I added some jQuery in there to remove the tumblr block tags while you are making your theme, as they make it brutal to layout.


Enjoy! .joe

foodfoto inc.サイトの作成に使ったツール・サービス | FJORD, LLC(合同会社フィヨルド)

fjord.jp

激しい( ´д`) “「Basecampでスケジュールを確認し、GithubからpullしてきてテーマをHamlで書き、ローカルのLokkaで確認してcommitし、Herokuにpushする」ということを全てデザイナーが出来るからこそ”

デザイナ( @machida さん)側のエントリーも参考に http://fjord.jp/love/696.html

Ruby -> Haml -> Rails3

Prossimo quick tutorial… in lavorazione ;-)

Escreva seu próprio código!

Calma ai pessoal, não venho aqui afirmar que sou contra a meta-programação, não é nada disso. O que considero má prática é a ideia de maquiar código html, css e javascript. Sei que o código de uma página HTML cheio de divs não é lá uma coisa bonita de se ver e sei também como é complicado mantê-lo limpo e fácil de entender. Soluções como HAML a primeira vista parece bem interessante, na própria página do projeto nós podemos encontrar um exemplo, digamos assim, tentador:

html.haml

#profile
  .left.column
    #date= print_date
    #address= current_user.address
  .right.column
    #email= current_user.email
    #bio= current_user.bio

html.erb

<div >
  <div class="left column">
    <div ><%= print_date %></div>
    <div ><%= current_user.address %></div>
  </div>
  <div class="right column">
    <div ><%= current_user.email %></div>
    <div ><%= current_user.bio %></div>
  </div>
</div>

Bem mais limpo, bem mais fácil de entender e quem sabe até mais produtivo. Então, por que diabos não uso isso? O que me incomoda é que sempre fica um pouco mais complicado resolver problemas no código gerado, é sempre uma dor de cabeça a mais, é um processo a mais! E outra, pra quê escrever código que me gera um html, se eu sei escrever código html? Não sei se estou conseguindo ser claro, mas apenas o fato de ter que me preocupar se o problema está no haml ou no código html gerado, ou se eu estou seguindo corretamente a sintaxe para que meu código seja corretamente gerado, são preocupações e processos desnecessárias. Quando falo de processos não estou falando apenas do processo humano, mas de processos de maquina mesmo, eu sei muito bem que interpretar um código haml para gerar um html não é um processo significante, mas ainda sim é um processo (tô exagerando?) . O que quero dizer é que evitar processos extras é uma boa prática, eu fico pra morrer quando encontro código estático sendo gerado, tipo, pra quê escrever este código “<%= link_to ‘Back’, sites_path %>” se ele vai sempre gerar o mesmo código html “<a href=”/sites”>Back</a>”, não é mais lógico escrever a versão “final” do código? Só para ressaltar, eu sei que estes pequenos processos A MAIS são insignificantes, porém usá-los frequentemente é no mínimo #$!**0!+?!, tem muita gente por ai usando um clientes.all em uma página que exibe apenas os clientes com débito, mas isso já é assunto pra outro post.

Sobre css, o sass tem atraído a atenção de muita gente. O sass não apenas deixa o código mais legível, mais bonito, o interessante do sass é o uso de variáveis. Sabe aquele cor que sempre repetimos em vários lugares do nosso css, a ideia é armazená-la em uma variável e chamá-la quando preciso, isso também ajuda quando precisamos mudar algum valor de uma propriedade que se encontra em muitos blocos, se esta propriedade estiver associado a uma variável, basta mudar o valor da variável. O sass traz umas coisas bem legais, vale a pena dar uma conferida, mas ele traz também os mesmos problemas do haml apresentados anteriormente, e outra, é bom lembra que hoje em dia até nos mais simples editores de texto encontramos opções de autocompletar e substituir trechos repetidos. A sacada do css é separar estilo de html, é evitar que tenhamos que inserir a propriedade color em todas as tags <p>, simplesmente declarando p{color:gray}. Estou satisfeito com css, não o considero um monstro e até o momento não sinto necessidade de simplificá-lo mais ainda.

Para javascript, temos o recém badalado CoffeScript. Não me aprofundei no assunto, nem mesmo o testei, mas pelo que li ainda não vi vantagem em usá-lo e deixar de escrever meu próprio código javascript. A dica que deixo é: “escreva seu próprio código!”

saya nak sangat buat project dengan Ruby Sinatra, Haml, MongoDB. tapi masih belum ada idea yang baik dan kesempatan masa :(

Loading more posts...