RSpec claims nil to be false

RSpec's be_false behaves unexpectedly:

nil.should be_false
# passes, as the expectation returns true

If you want to check for false, you need to do it like this:

nil.should == false
# fails as expected

Wat?

See also

RSpec: be_true does not actually check if a value is true

Don't use Ruby 1.9.2

Ruby 1.9.2 is very slow when loading files, especially starting Rails servers or running specs takes forever.

Do yourself a favor and upgrade to 1.9.3.

Rails 2's CookieStore produces invalid cookie data, causing tests to break

Note that this seems to affect only recent Rails 2 versions.

You will not encounter this until you are writing to the cookie more than once, but when doing so, integration tests (Cucumber) may break for you with this error:

You have a nil object when you didn't expect it!
You might have expected an instance of ActiveRecord::Base.
The error occurred while evaluating nil.[] (NoMethodError)

Background

The regular/short cucumber backtrace is not of any help but looking at the full trace reveals that ActionPack's `actio...

How much should I refactor?

The Rails community has been abuzz with object-oriented programming, SOLID principles, laws, design patterns, and other principles, practices, and patterns. We’ve (re)discovered new tools and techniques to separate and reuse logic, making code easier to test, understand, and maintain. Now that we’ve learned about all these new tools, when do we use them?

Beware of params with non-string values (nil, array, hash)

Recent rails security updates have shown that people make incorrect assumptions about the possible contents of the params hash.

Just don't make any! Treat it as what it is: potentially unsafe user input. For example:

/pages/edit?foo=   --> params == {:foo => ""}
/pages/edit?foo    --> params == {:foo => nil}
/pages/edit?foo[]  --> params == {:foo => [nil]} # at least in older rails 3 and in rails 2.x

Be especially wary about stuff like

User.find_by_password_reset_token(params[:password_reset_token])

I...

Use "overflow: hidden" to avoid floating elements from wrapping a container's text

Consider this HTML:

<div id="container">
  <div id="actions">
    <a href="#">Click me!</a>
  </div>
  <div id="content">
    Hello Universe! Hello Universe! Hello Universe! Hello Universe! Hello Universe! Hello Universe!
  </div>
</div>

If you want the actions element to float on the left, you'd just say this in your CSS:

#actions { float: left; }

Unfortunately, any content of the content's text will wrap underneath it:

![paja9.png](https://makandracards.com/makandra/9245-use-overflow-hidden-to-a...

Ruby: Natural sort strings with Umlauts and other funny characters

Why string sorting sucks in vanilla Ruby

Ruby's sort method doesn't work as expected with special characters (like German umlauts):

["Schwertner", "Schöler"].sort
# => ["Schwertner", "Schöler"] # you probably expected ["Schöler", "Schwertner"]

Also numbers in strings will be sorted character by character which you probably don't want:

["1", "2", "11"].sort
# => ["1", "11", "2"] # you probably expected ["1", "2", "11"]

Also the sorting is case sensitive:

...

Fix: Capybara is very slow when filling out fields in large forms

In large forms (30+ controls) new Capybara version become [extremely slow] when filling out fields. It takes several seconds per input. The reason for this is that Capybara generates a huge slow XPath expression to find the field.

The attached code patches fill_in with a much faster implementation. It's a dirty fix and probably does a lot less than Capybara's own fill_in so don't use it unless you are having problems with test suites that are unusable because of this...

Rails asset pipeline: Why relative paths can work in development, but break in production

The problem

When using the asset pipeline your assets (images, javascripts, stylesheets, fonts) live in folders inside app:

app/assets/fonts
app/assets/images
app/assets/javascripts
app/assets/stylesheets

With the asset pipeline, you can use the full power of Ruby to generate assets. E.g. you can have ERB tags in your Javascript. Or you can have an ERB template which generates Haml which generates HTML. You can chain as many preprocessors as you want.

When you deploy, Rails runs assets:precompile...

Browser Standards progress: CSS filter property

Some progress was made by browsers on implementing CSS filters like blur, greyscale or some other effects. You might already know the legacy CSS filter attribute that old IE versions used to perform DirectX transformations. Luckily these legacy filters are removed in IE10. The good news is, newest WebKit-based browsers like Chrome (18.0+) Safari and Mozilla Firefox expe...

Linux: How to add a task bar to VNC displays

If you are using VNC to run Selenium tests, it may be hard to see what's going on since by default there is no list of open windows and Alt+Tab won't work.

Solving that is easy:

  1. Install a panel of your choice (like lxpanel) which offers task switching:

    sudo apt-get install lxpanel
    

    (You can't use gnome-panel because it won't start twice -- but lxpanel does a good job)

  2. To have that panel appear on VNC screens by default, edit ~/.vnc/xstartup...

When the iPad won't play an MP4 video

I had trouble serving an MP4 video to my iPad. Although the video complied with all the specs (H.264 codec, up to 1080p, 30 FPS) I always got this error:

This video could not be loaded, either because the server or network failed or because the format is not supported: http://10.40.0.177:3000/video.mp4

After spending a lot of time fighting this issue, I tried to upload the same unchanged video file to a production server (Apache / Passenger). It worked immediately. I guess iOS is picky about some HTTP header that my local HTTP server (Th...

Plotting graphs in Ruby with Gruff

Geoffrey Grosenbach has created Gruff for easily plotting graphs. It is written in pure Ruby and integrates with Rails applications.

It provides features as automatic sizing of dots and lines (the more values, the thinner the graph's elements), custom or predefined themes, different styles (bar, line, dot and many more) and multiple graphs in one chart.

Installation

In your Gemfile:

gem 'rmagick', :require => false
gem 'gruff'

Then run bundle install (and don't forget to restart your development server.)

Usage

This i...

Guide to localizing a Rails application

Localizing a non-trivial application can be a huge undertaking. This card will give you an overview over the many components that are affected.

When you are asked to give an estimate for the effort involved, go through the list below and check which points are covered by your requirements. Work with a developer who has done a full-app localization before and assign an hour estimate to each of these points.

Static text

  • Static strings and template text in app must be translated: Screens, mailer templates, PDF templates, helpe...

RubyMine: Set specific Ruby version per project

If your project uses another version than your default Ruby, RubyMine will give you incorrect inspections, for example.\
Here is how to switch which Ruby you use in RubyMine.

  1. File → Settings (Or press Ctrl+Alt+S)
  2. Select "Ruby SDK and Gems" from the left pane
  3. Switch your "Ruby interpreter".

Though it may seem you are changing a global setting here, this is in fact a per-project setting, as are all things you change in the "Project Settings [your_project_name]" area of the global settings dialog.

When you switch to another proje...

Compress bitmap images within PDF files

Embedding bitmap images within PDF sometimes results in large files because the bitmaps are not compressed. If you don't need high quality images within the resulting PDF file, you can use ghostscript to compress embedded images:

ghostscript -sDEVICE=pdfwrite -dCompatibilityLevel=1.4 -dPDFSETTINGS=/ebook -dNOPAUSE -dQUIET -dBATCH -sOutputFile=new-smaller-file.pdf large-original-file.pdf

Note that your PDF printer (or similiar generation tools) also often come with a compression setting for embedded raster images.

You can put this ...

Sync confidential files between unixes using cloud storage and encfs

Note: You might also want to check out BoxCryptor which does pretty much the same, and is supported across many more platforms. I just didn't want to use Dropbox...

I use Ubuntu One to automatically sync confidential files between my machines. The encryption is done via encfs, which is a file-based encryption that simply puts encrypted versions of files from one folder into another. This is well-suited for cloud storage, since it allows syncing single files, not whole crypt containers.

Recipe

I'll ass...

Bundle capistrano

Capistrano recently had some API changes that can results in deploys not working when running with old deploy.rb files.

So let's bundle it. Put capistrano into your Gemfile, like this:

# Gemfile

group :deploy do
  gem 'capistrano'
  gem 'capistrano_colors'
end

It's possible you need to do a bundle update net-ssh to get things running.

Now double check that all your custom hooks are actually still called. One candidate might be an after deploy:symlink hook that has been renamed into `after deploy:creat...

How to use pessimistic row locks with ActiveRecord

When requests arrive at the application servers simultaneously, weird things can happen. Sometimes, this can also happen if a user double-clicks on a button, for example.

This often leads to problems, as two object instances are modified in parallel maybe by different code and one of the requests writes the results to the database.

In case you want to make sure that only one of the requests "wins", i.e. one of the requests is fully executed and completed while the other one at least has to wait for the first request to be completed, you ha...

Aspect Oriented Programming in Ruby

Slides presenting ways to integrate the ideas of Aspect-Oriented Programming in Ruby.

Outline

  • Why Aspect-Oriented Programming?
  • AOP in Java and AspectJ (a Review).
  • AOP in Ruby.
    • What you can do today.
    • Example AOP-isms in Ruby on Rails.
  • Aspect-Oriented Design.
  • The AOP Promise for Tomorrow.

You cannot use :before or :after on img in CSS

Though the W3C even gives it as an example, no browser actually supports this CSS:

img:before {
  content: "something";
}

Browsers will simply not render anything when doing that on images (Fun fact: It worked in an older version of Opera but got dropped).\
The same applies to the :after pseudo-element.

This makes me sad.

You can try using jQuery instead.

Use a special version of Chrome for selenium (and another for your everyday work)

Sometimes you need a special version of chrome because it has some features you need for testing, like in this card. You do not need to use that Version apart from tests, because you can tweek selenium to use a special version that you set in your environment:

# features/support/chrome.rb
require "selenium/webdriver"

Capybara.register_driver :chrome320x480 do |app|
  
  if driver_path = ENV["CHROME_SELENIUM_BIN...

Set the accept-language of Chrome in selenium tests

You can set the resolution and user agent used in selenium tests with chrome with the method described in this card, but you can also set the accept-language and other profile settings if you do this:

# features/support/chrome.rb
require "selenium/webdriver"


Capybara.register_driver :chrome320x480 do |app|
  args = []
  args << "--window-...

Run Chrome in a specific resolution or user agent with Selenium

When you want to test how an web-application reacts in a specific resolution, you can set up a specific Selenium driver for some tests:

 Before('@chrome320x480') do
     Capybara.current_driver = :chrome320x480
 end

 After('@chrome320x480') do
    Capybara.use_default_driver 
 end

You can use either chromium or chrome beta (as of 2012.05 the Version "19.0.1084.41 beta" works), or any other member of the family. It only needs to supports the "--window-size" command-line switch. [See this list](http://peter.sh...