When sessions, cookies and Clearance tokens expire and how to change it

Expiration of Rails sessions

By default Rails sessions expire when the user closes her browser window.

To change this edit your config/initializers/session_store.rb like this:

ActionController::Base.session = {
  :key          => '...',
  :secret       => '...'
  :expire_after => 10.years
}

In older Railses the initializer is not available. Set the option in the environment.rb instead:

config.action_controller.session = {
  :key          => '...',
  :secret       => '...'

...

Know your Haml comments

There are two distinct ways of commenting Haml markup: HTML and Ruby.

HTML comments

This will create an HTML comment that will be sent to the client (aka browser):

/= link_to 'Example', 'www.example.com'

This produces the following HTML:

<!-- = link_to 'Example', 'www.example.com' -->

Only use this variant if you need the comment to appear in the HTML.

Ruby comments

This will comment code so it will not be sent to the client:

-# = link_to 'foo'

99% of the time you'll be adding notes f...

Difference between respond_to/format and params[:format]

To return non-HTML responses (like XLS spreadsheets), we usually use the

respond_to do |format|
  format.xls do
    # send spreadsheet
  end
end

This is often, but not always the same as checking for params[:format] == :xls, so don't rely on this when e.g. one format checks for authorization and the other doesn't.

params[:format] is only set when a user explicitly puts a .xls at the end of the URL.

The format.xls block also responds when the user's browser requests the application/excel MIME type.

If Internet Explo...

Bundler for Rails 2.3.x

Update RubyGems and Passenger

Bundler requires Rubygems >= 1.3.6. Run gem update --system if you have an older version.
It also is not compatible with older versions of passenger, so bring that up to date as well (2.2.15 works).

If you installed RubyGems through apt (which you should never do!), you may see a message giving you a hint to use apt to update.
Some people advise to install the 'rubygems-update-1.3.7' gem on Ubuntu systems if you used apt to install RubyGems.
I did that - and lost all...

Recursively remove unnecessary executable-flags

Sometimes files attain executable-flags that they do not need, e.g. when your Windows VM copies them over a Samba share onto your machine.

From inside your Rails project directory call regularly:

geordi remove-executable-flags

Runs chmod -x on Ruby, HTML, CSS, image, Rake and similar files.


This script is part of our geordi gem on github.

Unobtrusive jQuery to toggle visibility with selects and checkboxes

Use this if you want to show or hide part of a form if certain options are selected or boxes are checked.

The triggering input gets an data-selects-visibility attribute with a selector for the elements to show or hide, like

<%= form.select :advancedness, [['basic', 'basic'], ['advanced', 'advanced'], ['very advanced', 'very_advanced]], {}, :"data-selects-visibility" => ".sub_form" %>

The elements that are shown/hidden look like

<div class="sub_form" data-show-for="basic"> 
  only shown for advancedness = basic 
</div>

...

Marry Capybara with SSL-enabled applications

Capybara does not play nice with sites that have some actions protected by SSL, some not. A popular way to implement this in Rails is using the ssl_requirement plugin by DHH, which redirects a requests from HTTP to HTTPS if the requested action requires SSL and vice versa.

Capybara follows the redirect, but seems to forget the changed protocol for the next request. The only hack-free workaround right now is to use URLs in lieu of paths everywhere (links, form actions).

For a hackful fi...

Get TinyMCE editor content as HTML

tinyMCE.activeEditor.getContent()

Autofocus a form field with HTML5 or jQuery

In Webkit you can use the HTML5-attribute autofocus:

= form.text_field :title, :autofocus => 'autofocus'

Here is a jQuery fallback for browsers that don't speak HTML5:

var Autofocus = {

  supported: function() {
    return 'autofocus' in document.createElement('input');
  },

  fake: function() {
    $('[autofocus]').focus();
  },

  extend: function() {
    Autofocus.supported() || Autofocus.fake();
  }

};

$(Autofocus.extend);

Cucumber Webrat steps

Most of these will not work in newer projects because these use the Capybara/Rack::Test combo in lieu of Webrat.

Find input fields

Then /^there should be a "([^"]+)" field$/ do |name|
  lambda { webrat.current_scope.send(:locate_field, name) }.should_not raise_error(Webrat::NotFoundError)
end

Then /^there should be no "([^"]+)" field$/ do |name|
  lambda { webrat.current_scope.send(:locate_field, name) }.should raise_error(Webrat::NotFoundError)
end

Find html content

Then /^I should see "([^\"]*)...

Release gem; Deploy gem; Update a gem created with Jeweler

Until May 2011 our gems have been created with Jeweler, which is a helper library to package code into a gem. You know a gem was cut with Jeweler if you see the word jeweler in a gem project's Rakefile.

This note describes how to update a gem that was cut using Jeweler. Note that this can be traumatic the first time. It would be great to have an easier workflow for this. Jeweler is deprecated these days because you can

**now [cut gems more easily using Bundler](https://makandracards.com/makandra/1229-updat...

Aggregated RSpec/Cucumber test coverage with RCov

With defaults, RCov doesn't work the way you how you would like it to. To create a nice test coverage report, copy the attached file to lib/tasks/rcov.rake. After that rake rcov:all will run all RSpec examples and Cucumber features. The report will be written RAILS_ROOT/coverage/index.html.

Here is what the task does in detail:

  • Generates aggregated coverage of both RSpec and Cucumber
  • Works with Rails 2 and Rails 3
  • Reports for app/**/*.rb and nothing else
  • If called with an environment variable IGNORE_SHARED_TRAITS=true it ...

Parse XML or HTML with Nokogiri

To parse XML-documents, I recommend the gem nokogiri.

A few hints:

  • xml = Nokogiri::XML("<list><item>foo</item><item>bar</item></list>") parses an xml string. You can also call Nokogiri::HTML to be more liberal about accepting invalid XML.
  • xml / 'list item' returns all matching nodes; list item is used like a CSS selector
  • xml / './/list/item' also returns all matching nodes, but .//list/item is now an XPath selector
    • XPath seems to be triggered by a leading ....

Automatically build sprites with Lemonade

How it works

See the lemonade descriptions.

Unfortunately, the gem has a few problems:

  • it does not work with Sass2
  • it always generates all sprites when the sass file changes, which is too slow for big projects
  • it expects a folder structure quite different to our usual

All these problems are solved for us, in our own lemonade fork. This fork has since been merged to the original gem, maybe we can use t...

Convert Haml to ERB

This is about converting Haml to ERB and not the other way round which you probably want!

This process can not be automated 100%, but you can still save time.

First do

script/plugin install http://github.com/cgoddard/haml2erb.git

Then in the console type

hamls = Dir["app/views/**/*.haml"] - ['app/views/layouts/screen.html.haml'];
hamls.each do |haml| 
  puts haml
  erb = haml.sub(/\.haml$/, '.erb')
  File.open(erb, 'w') do |file| 
    file.write Haml2Erb.convert(File.read(haml)) 
  end
end

After th...

Typical .gitignore

log/*
tmp/*
storage/*
db/*.sqlite3
db/schema.rb
db/structure.sql
public/system
.project
.idea/
public/javascripts/all*
public/stylesheets/all*
public/stylesheets/*.css
config/database.yml
*~
*#*
.#*
.DS_Store
webrat-*.html
capybara-*.html
rerun.txt
coverage.data
coverage/*
dump_for_download.dump
.~lock.*
.*.swp
C:\\nppdf32Log\\debuglog.txt

Configuring Git with .gitconfig

Basic configuration

Please keep this config simple. It should be a starting point for new developers learning Git.

[user]
  name = Your Name
  email = your.name@domain.com

[branch]
  sort = -committerdate
[color]
   ui = auto
[color "branch"]
  current = yellow reverse
  local = yellow
  remote = green
[color "diff"]
  whitespace = white reverse
  meta = blue reverse
  frag = blue reverse
  old = red
  new = green
[color "status"]
  added = green
  changed = yellow
  untracked = cyan
[interactive]
  singlekey = true # Do not requir...