Git Cheatsheet

Make sure you understand differences between git's areas (such as stash, workspace, upstream, etc.) and what commands affect which areas.

javan/whenever - GitHub

Whenever is a Ruby gem that provides a clear syntax for writing and deploying cron jobs.

Validations on associated objects

Validations that need to access an associated object may lead to some trouble. Let's exemplify that using this example:

class Project < ActiveRecord::Base
   has_one :note
end

class Note < ActiveRecord::Base
   belongs_to :project
end

Now say we need a validation that ensures that a description is set (validates_presence_of :description) within Note but only if the Project has a flag called external set to true. The following code will lead to some problems as the associated object is not present when creatin...

Speed up Capistrano deployments using a remote cached copy of repository

You can seriously speed up deployments with Capistrano when using a local git repository on the server you are deploying to.

Simply add

set :deploy_via, :remote_cache
set :copy_exclude, [ '.git' ]

to your config/deploy.rb and Capistrano will create a clone in shared/cached-copy. This will be updated using git pull when deploying which transfers less bytes and is usually much faster. If deploy_via is set to use default settings (being "export"), Capistrano will do a full clone of the repository from your git host otherwi...

Apprise - The attractive alert alternative for jQuery

An alert alternative for jQuery that looks good. Apprise is a very simple, fast, attractive, and unobtrusive way to communicate with your users. Also, this gives you complete control over style, content, position, and functionality. Apprise is, more or less, for the developer who wants an attractive alert or dialog box without having to download a massive UI framework.

Capistrano 2: Which Capistrano hooks to use for events to happen on both "cap deploy" and "cap deploy:migrations"

When deploying an application with "cap deploy" by default [1] you only deploy your code but do not run migrations. To avoid an application to be running with code which requires database changes that did not happen yet you should use cap deploy:migrations.

The problem

Let's say that you have something like that in your config/deploy.rb to create a database dump every time you deploy:

before 'deploy', 'db:dump'

This will not be called for cap deploy:migrations. The same applies to other things that are ho...

Why a Rails flash message is shown twice

You set a flash message and it shows up as it should. However, it is displayed again the next time you follow a link. Here is why:

You have to differentiate between a render and a redirect_to because a flash message is only deleted after a redirect. If you want a message to be seen in the next request after a redirect, use flash[]. If you want a message to be seen in the current request, use flash.now[].

Workaround for the lazy

If you cannot be bothered to decide which flash hash to use, or if the fl...

Ignore an error class with Airbrake

Airbrake (formerly Hoptoad) already ignores certain errors like InvalidAuthenticityToken by default (see Airbrake::Configuration::IGNORE_DEFAULT).\
To ignore additional classes of errors, put this into config/initializer/airbrake.rb:

Airbrake.configure do |config|
  config.ignore << 'ActiveRecord::IgnoreThisError'
end

You probably also want to ignore ActionController::MethodNotAllowed and ActionController::UnknownHttpMethod exceptions.

See the github page for more options on h...

Haml and Sass 3.1 are Released

Sass now comes with user-defined functions, keyword arguments, list manipulation. Haml and Sass are now two separate gems.

HTML5 Presentation

Awesome presentation for the new HTML5 features we will get to play with. This presentation should probably be viewed in Chrome only.

How to translate “business value” of things that are technically important

User Stories should describe what a user wants the system to do. Purely technical tasks should usually be implemented as part of a User Story. But, sometimes there are technical tasks which cannot be directly linked to customer value. Things like “Upgrade to MySQL 6.0″ or “replace magic numbers with enums” need to be done. How can you prioritize these critical chores against User Stories? How can you make the product owner aware of the importance of such tasks (and the business risks of procrastination)?

Rails jQuery UJS: Now Interactive

We can now plug into every facet of the Rails jQuery UJS adapter, binding to custom events, and even customizing internal functions, without hacking or monkey-patching the rails.js file itself.

Saving application objects in your session will come back to haunt you

If you save a non-standard object (not a String or Fixnum, etc) like the AwesomeClass from your application in the session of visitors be prepared that some time you will get this exception:

ActionController::SessionRestoreError: Session contains objects whose class definition isn't available. Remember to require the classes for all objects kept in the session. (Original exception: ...)

This happens when you remove your AwesomeClass but users come back to your site and still have the serialization of such objects in their session....

How to: Apache logs on a daily basis without logrotate

If you want to have a new log file every day automatically, but avoid using logrotate, the CustomLog directive is your friend:

CustomLog "|/usr/sbin/rotatelogs /opt/www/awesome-project/log/access.%Y-%m-%d.log 86400" combined

Adding that to your site's vhost will create log files that include the current date in their name, like access.2011-04-20.log, without any need to restart the web server every night (like logrotate does).

The last argument above is the rotation time in seconds -- here being 86400 (= 60 * 60 * 24) which ca...

How to fix strangely disappearing or misbehaving forms

You most likely have a form element inside another form element. Don't do that. Ever.

Firefox and Chrome will discard the first form nested inside another form (but for some reason keep others). Internet Explorer will possibly act like nothing is wrong -- but break (send the outer form) when you submit.

If your application behaves normal at first but removes forms from the DOM when you Ajax around, this could be the cause. Remember this note when you think your browsers are broken once again and check for such things thoroughly bef...

Use CSS attribute selectors with Capybara

You can use CSS attribute selectors in your step definitions like this:

Then /^the page should have a meta description "([^"]+)"$/ do |description|
  page.should have_css("meta[name=\"description\"][content=\"#{description}\"]")
end

Note that you need to always quote attribute values or you will get a Nokogiri parsing error like this:

unexpected 'foo' after 'equal' (Nokogiri::CSS::SyntaxError)

Collect an array of IDs from any object

The Edge Rider gem will define a method collect_ids on your ActiveRecord models, scopes, integer scalars and collections, which will return a list of their IDs:

User.last.collect_ids # => [9]
[User.first, User.last].collect_ids # => [1, 9]
User.active.collect_ids # => [4, 5, 6]
[4, 5, 6].collect_ids # => [4, 5, 6]
7.collect_ids #=> [7]

This allows you to parametrize scopes with a variety of argument types:

class Note < ActiveRecord::Base
  named_scope :for_users, lamb...

Fix "undefined method `destroy'" in reset_session

This is a bug in Rails 2.3.11 which will be fixed in a future maintenance release.

Until then you can copy the attached initializer to config/initializers.

thoughtbot/capybara-webkit

A capybara driver that uses WebKit via QtWebKit.

makandra/consul

Our new scope-based authorization gem for Ruby on Rails has been released. This might one day replace Aegis as our standard authorization solution.

List your current Git remotes

To display a list of your current Git remotes and their endpoints, you can say

git remote -v

The output looks like this:

brady8	https://github.com/brady8/aegis.git (fetch)
brady8	https://github.com/brady8/aegis.git (push)
origin	git@github.com:makandra/aegis.git (fetch)
origin	git@github.com:makandra/aegis.git (push)

Convert RDoc markup to HTML

If you want to convert a README.rdoc file to HTML, say this from a shell:

rdoc README.rdoc

You will find the generated HTML in doc/index.html.

If you do this while working on one of our gems, please .gitignore everything in doc and don't commit the generated HTML.

RDoc markup reference

Documentation for the horrible RDoc syntax.

Why preloading associations "randomly" uses joined tables or multiple queries

ActiveRecord gives you the :include option to load records and their associations in a fixed number of queries. This is called preloading or eager loading associations. By preloading associations you can prevent the n+1 query problem that slows down a many index view.

You might have noticed that using :include randomly seems to do one of the following:

  1. Execute one query per involved table with a condit...