Configuring ActionMailer host and protocol for URL generation

When you generate a URL in a mailer view, ActionMailer will raise an error unless you previously configured it which hostname to use.

There are two options to set the default_url_options of ActionMailer:

  1. Hardcoded solution (preferred solution when using Rails with ActiveJob/Sidekiq or Cronjobs)
  2. Dynamic solution

1. Hardcoded solution

When you are sending mails from outside the request cycle, e.g. ActiveJob/Sidekiq or Cronjobs, y...

Popular mistakes when using nested forms

Here are some popular mistakes when using nested forms:

  • You are using fields_for instead of form.fields_for.
  • You forgot to use accepts_nested_attributes in the containing model. Rails won't complain, but nothing will work. In particular, nested_form.object will be nil.
  • The :reject_if option lambda in your accepts_nested_attributes call is defined incorrectly. Raise the attributes hash given to your :reject_if lambda to see if it looks like you expect.
  • If you are nesting forms into nested forms, each model involved ne...

How to build the perfect number of blank records for a nested form

When you render a nested form for a Movie which has_many :actors, you want to render the right number of blank Actor forms. The right number means:

  • A minimum number of blank forms so the user can add more Actors to an existing Movie, e.g. 2.
  • A minimum total number of forms (both blank and pre-filled) so the user sees more than just 2 blank Actor forms when she is entering Actors for the first time, e.g. 5.

For the example above, this is the desired progression of the number of blank forms:

| Number of actors | Number of ...

Force Google Chrome to run in English on Linux

If you need Google Chrome to run in English, and your system locale is a non-English one, you have two options:

  • Switch your system to an English locale
  • Head over to /opt/google/chrome/locales/ and remove any .pak files except those starting with “en”. They reappear when Chrome gets updated.

This may help you running your Selenium tests using the Chrome driver on applications that choose the language from what the browser sends as preferred language (which Chrome guesses from your system locale).

How to use helper methods inside a model

Simple

If you want to use a helper_method my_helper_method inside a model, you can write

ApplicationController.helpers.my_helper_method

When using multiple helpers

delegate :helpers, to: ApplicationController
helpers.my_helper_method
helpers.my_other_helper-method

More flexible

If you need a bit more flexibility, for example if you also need to override some methods, you can do this:

class HelperProxy < ActionView::Base
  include ApplicationController.master_helper_modu...

How to upgrade RubyMine

This card explains how to upgrade an existing RubyMine installation to a newer version. If you're installing RubyMine for the first time, see install RubyMine under Ubuntu. You might also consider installing RubyMine with snap, so it can receive automatic updates (also described in the install card).


This procedure ensures that an update does not totally break your IDE, as it allows you to keep both the previous and the new version of RubyMine:

  1. [Download the newest version](http://www.jetbrains.com/ruby...

Helpers to render (money) amounts

When rendering a number, you want to pretty up the string coming from #to_s:

  • Render 0.0 as 0
  • Sometimes require a minimum number of digits after the decimal separator
  • Change the decimal separator from . to , in some European countries
  • Render a dash if the given amount is nil

The attached helper that does just that. Some usage examples with their resulting strings:

Invocation Result
amount(0) 0
amount(0.0) 0
amount(0.5) 0,5
amount(1.5, :minimum_precision => 2) 1,50
`amo...

Stubbed class methods in RSpec 1 remain stubbed in other examples

I encountered a bug in RSpec 1.x where stubbed class methods ("static methods") would not be unstubbed before the next example, causing it to fail. This behavior can come and go as you edit your specs, since this can change the order in which RSpec evaluates your .rb files.

I was not able to find a fix for this behavior. Calling #rspec_reset und #unstub!(:method) on the class after the example did not help. I know for sure that stubbing static methods has not been a problem in many other projects. I encountered the bug while working o...

A nicer way to run RSpec and/or Cucumber

geordi, our collection of awesome shell scripts, has been extended by three scripts to help you call RSpec or Cucumber:

cuc

This script runs Cucumber the way you want it:

  • Prints some line feeds to easily find your test results when you come back to the console later
  • Configures Cucumber to use cucumber_spinner if it is available in your Gemfile
  • Runs Cucumber under bundle exec
  • Uses an old version of Firefox for Selenium (Javascript) features...

Soft-scroll to an anchor with jQuery

This snippet makes links that refer to an anchor (like "<a href="#something">...</a>") scroll softly to it.\
In this example we only do it for links that also own a data-animate attribute.

$('a[href^="#"][data-animate]').live('click', function() {
  var hash = $(this).attr('href');
  var offset = $(hash).offset();
  if (offset) {
    $('html, body').animate({ scrollTop: offset.top }, 'slow');
    location.hash = hash;
    return false;
  }
});

Note that this could basically work for any element whos...

Semantic markup standard for search engines

If you would like to enrich your website with semantic markup like contact data, places or events you should have a look at schema.org. "Search engines including Bing, Google and Yahoo! rely on this markup to improve the display of search results, making it easier for people to find the right web pages."

The following example from the schema.org documentation shows you how to describe a movie with semantic markup:

<div itemscope itemtype ="http://schema.org/Movie">
  <h1 itemp...

Matching elements on complex web pages with Webrat

XPath matchers can be combined with CSS-selector matchers. This is really useful if not, for example, the content of an element should be matched but the element itself like in the following example. Here a form is used to display data as default value in its input elements. This can be the case in web applications in which data should be edited easily without additional clicks.

Using StaticMatic for static pages

Update: Staticmatic will not be further developed. They suggest to switch to middleman.


If you need to make a static web page and find yourself missing all your Rails comforts, take a look at StaticMatic.

This works like an extremely stripped down version of Rails, giving you

  • HAML
  • SASS
  • helpers
  • partials

When done, everything is simply compiled to s...

Center a float horizontally

This card shows you how to center a float horizontally in CSS. Also: find out what techniques are available for your use case and browser requirements in the card linked below.

Note: We have card with all CSS centering options. You probably want to head over there and get an overview over what techniques are available for your use case and browser requirements.


If you cannot use display: inline-block, centering a float ...

Setting up FreeBSD as Virtual Machine in VMware

Install FreeBSD

  • Download a suitable image from this site
  • Select File > New… to and follow the instructions, choose the .iso file you downloaded as image file
  • Start the new virtual machine and follow the instructions

Install VMware Tools

Choose Virtual Machine > Install VMware Tools from the VMware menu, then as root:

^
# install required packages
pkg_add...

Conditional comments for Internet Explorer with Haml

Internet Explorer 5+ is aware of conditional comments that let you target HTML for selected versions of IE. For example the HTML below would ask users of IE 6 and IE 7 to install Firefox:

<!--[if lt IE 8]>
  <a href='http://www.mozilla.com/en-US/firefox/'>Get a real browser</a>
<![endif]-->

You might wonder how to express such a conditional comment in your favorite templating language, Haml. You might even have converted a template back to ERB just for this ...

Playing audio in a browser

If you want to play music or sounds from a browser, your choice is to use either Flash or the new <audio> tag in HTML5. Each method has issues, but depending on your requirements you might not care about all of them.

Flash

  • Works in all desktop browsers, even Internet Explorer. Does not work on iPads or iPhones.
  • Requires you to embed a Flash component into your page which will later play the audio for you.
  • Can play MP3s or Wave files. Cannot play OGG Vorbis audio.
  • Cannot reliably seek to a given position when playing VBR-enco...

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.

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...

Calling a helper method with the same name as your current partial

Partials always define a local variable with the same name as themselves. E.g. when you are in _recent_users.html.erb, a local variable recent_users will be defined and overshadow any helper method that is also called recent_users().

If you would like to use a helper method recent_users() in a partial _recent_users.html.erb you can say this in the partial template:

<% recent_users = self.recent_users() %>
<% recent_users.each do |user| %>
  ...
<% end %>

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.

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...

Default views in Rails 3.0 with custom resolvers

It is common in Rails 3.0 applications that you want to provide default views for a group of controllers. Let’s say you have a bunch of controllers inside the Admin namespace and you would like each action to fallback to a default template. So if you are rendering the index action for Admin::PostsController and “app/views/admin/posts/index.html.*” is not available, it should then render “app/views/admin/defaults/index.html”.

Since Rails 3.0, we have a new abstraction called resolvers that holds the logic to find a template.

Opera: How to use outlining for better layout debugging

I prefer using Opera's "User mode" to toggle an outlining of HTML elements quickly. This helps greatly when you want to see the actual dimensions of elements, e.g. for floating elements inside containers, instead of opening up the Dragonfly inspector every time.

Navigate to View → Style → "Manage Modes..." and tick the checkboxes like in the attached image. Then, switch to the User Mode by pressing the shortcut (Shift+G for the 9.2-compatible layout or for the default layout with enabled "single-key shortcuts") and select "Outline" from...