Raise when there's a I18n translation missing

The translation method translate and its alias t have bang brothers: translate! and t!. They will raise I18n::MissingTranslationData on a missing translation instead of printing a string like translation missing: de.custom.failure.

To turn on raising globally, you need to replace the default exception handler. The attached initializer makes I18n just raise any exception (in a development or test environment).

Font sizing with rem - Snook.ca

CSS3 comes with new unit rem. It works like em but it is always relative to the <html> element instead of the parent element.

rem units are supported by all browsers and IE9+.

Testing shared traits or modules without repeating yourself

When two classes implement the same behavior (methods, callbacks, etc.), you should extract that behavior into a trait or module. This card describes how to test that extracted behavior without repeating yourself.

Note that the examples below use Modularity traits to extract shared behavior. This is simply because we like to do it that way at makandra. The same techniques apply for modules and overriding self.included.

Example
---...

RSpec: Where to put custom matchers and other support code

Custom matchers are a useful RSpec feature which you can use to DRY up repetitive expectations in your specs. Unfortunately the default directory structure generated by rspec-rails has no obvious place to put custom matchers or other support code.

I recommend storing them like this:

spec/support/database_cleaner.rb
spec/support/devise.rb
spec/support/factory_bot.rb
spec/support/vcr.rb
spec/support/matchers/be_allowed_access.rb
s...

RSpec: Where to put shared example groups

Shared example groups are a useful RSpec feature. Unfortunately the default directory structure generated by rspec-rails has no obvious place to put them.

I recommend storing them like this:

spec/models/shared_examples/foo.rb
spec/models/shared_examples/bar.rb
spec/models/shared_examples/baz.rb
spec/controllers/shared_examples/foo.rb
spec/controllers/shared_examples/bar.rb
spec/controllers/shared_examples/baz.rb

To ma...

Render a view from a model in Rails

In Rails 5 you can say:

ApplicationController.render(
  :template => 'users/index',
  :layout => 'my_layout',
  :assigns => { users: @users }
)

If a Request Environment is needed you can set attributes default attributes or initialize a new renderer in an explicit way (e.g. if you want to use users_url in the template):

ApplicationController.renderer.defaults # =>
{
  http_host: 'example.org',
  https:      false,
  ...
}
...

How to use the Capistrano 2 shell to execute commands on servers

Capistrano 2 brings the shell command which allows you to run commands on your deployment targets.
There is also invoke to run a command directly from your terminal.

Both commands allow running Capistrano tasks or shell commands, and scope to individual machines or machine roles.

Unfortunately Capistrano 3 does not include these commands any more.

cap shell

Basics

First of all, spawn a Capistrano shell (we're using the multistage extension here):

$ cap staging shell

In your "cap" shell you can now run Capistrano ta...

Rails: Disable options of a select field

Simply give the select helper an option :disabled, passing either a single value or an array. You need to specify the option's value, not its text.

= form.select :country, Address.countries_for_select, :include_blank => true, :disabled => ['disabled-value1', 'disabled-value-2']

Also see Cucumber: Check if a select field contains a disabled option on how to test this.

Automated "git bisect" will make your day

So you're hunting down a regression (or just a bug) and want to use git bisect to find out when it was introduced? Smart kid.
If you have a shell command ready to reveal if your current state is good or bad, you can have git do most of the work for you.

Using git bisect run <your command> you can tell git that your command will reveal the issue; git on the other hand will use the return value of that call to decide if the state is good or bad.
...

Consul 0.9 lets you optimize records checks

Consul 0.9 comes with many new features to optimize powers that only check access to a given record. e.g. Power.current.post?(Post.last). See below for details.

Powers that only check a given object

Sometimes it is not convenient to define powers as a collection. Sometimes you only want to store a method that
checks whether a given object is accessible.

To do so, simply define a power that ends in a question mark:

class Power
  ...

  power :upd...

Cryptic Ruby Global Variables and Their Meanings

The linked page lists and explains global Ruby "dollar" variables, such as:

  • $: (load path)
  • $* (ARGV)
  • $? (Last exit status)
  • $$ (PID)
  • $~ (MatchData from last successful match)
  • ...and many more you'll need when reading weird code.

Regex

  • $~ (last MatchData)
  • $1 $2 $3 $4 (match groups from the last pattern match)
  • $& (last matched string)
  • $+ (last match group)
  • `$`` (the string before the last match)
  • $' (the string after the last match

See [this extensive list of variables](http://www.tu...

Do not try to "slice" on an ActionController::CookieJar

The cookies object in your controllers and views is a ActionController::CookieJar and even though that class inherits from Hash and often behaves like one, you can not call slice on it to select only a subset of cookies. Why? Because Hash#slice calls self.class.new -- which in case of a CookieJar just won't work.

Unfortunately, you can't even say cookies.to_hash and slice on that, just because CookieJar#to_hash is inherited from Hash and will just return self. Bummer.

You need to do it yourself, for example by usin...

Bash: How to generate a random number within given boundaries

$RANDOM on bash returns a random integer between 0 and 32767.

echo $RANDOM
9816
echo $RANDOM
30922

If you want to limit that to a certain maximum, you can just compare against the modulus of that maximum + 1. \
For example, the following will yield results between 0 and 9:

echo $(($RANDOM % 10))
5
echo $(($RANDOM % 10))
9

Note that this skews random numbers to the lower regions of your boundaries in most cases.

ActionView::Template::Error (dump format error for symbol(0x6d))

I recently encountered the error above when I was running selenium tests.

Thanks to a post on stackoverflow I found out that clearing all files in tmp/cache in my project folder made the issue go away.

Sprites with Compass

Using CSS sprites for background images is a technique for optimizing page load time by combining smaller images into a larger image sprite.

There are ongoing arguments on how useful this still is, as modern browsers become more comfortable to load images in parallel. However, many major websites still use them, for example amazon, [facebook](...

Switch to a recently opened tab with Cucumber

Similar to closing an opened browser window, spreewald now supports the I switch to the new browser tab step.

Info

See the Spreewald README for more cool features.

You can use it to test links that were opened with a link_to(..., :target => '_blank') link or other ways that create new tabs or windows.

Important

This only works with Selenium ...

Live CSS / view reloading

Next time you have to do more than trivial CSS changes on a project, you probably want to have live CSS reloading, so every time you safe your css, the browser updates automatically. It's pretty easy to set up and will safe you a lot of time in the long run. It will also instantly reload changes to your html views.

Simply follow the instructions below, taken from blog.55minutes.com.

Install CSS live reload (only once per project)

  1. Add th...

Howto remove the location hash without causing the page to scroll

Set the hash to a dummy hash which doesn't hit any id at your page, for example:

window.location.hash = "_";

Note

  • If you'd set the hash to "" it causes the page to scroll to the top because the hash "#" by itself is equivalent to "_top".
  • If you'd set window.location.href = "..." to get rid of the "#", you cause the browser to reload the page what is most likely not intended.

Common mistakes when storing file uploads with Rails

1. Saving files to a directory that is not shared between deploys or servers

If you save your uploads to a made up directory like "RAILS_ROOT/uploads", this directory goes away after every deploy (since every release gets a new). Also this directory is not shared between multiple application servers, so your uploads are randomly saved to one local filesystem or another. Fixing this afterwards is a lot of fun.

Only two folders are, by default, shared between our application servers and deployments: "RAILS_ROOT/storage" and `"RAILS...

Upgrading Rails 2 from 2.3.8 through 2.3.18 to Rails LTS

This card shows how to upgrade a Rails 2 application from Rails 2.3.8 through every single patch level up to 2.3.18, and then, hopefully, Rails LTS.

2.3.8 to 2.3.9

This release has many minor changes and fixes to prepare your application for Rails 3.

Step-by-step upgrade instructions:

  1. Upgrade rails gem
  2. Change your environment.rb so it says RAILS_GEM_VERSION = '2.3.9'
  3. Change your ...

ActiveRecord.select

Active Record's select method allows you to make use of the power of MySQL select statements. On the one hand it allows you to select specific fields.

Post.select("content")

results in the following query:

"SELECT content FROM `posts`"

This means that your models will be initialized with only the content attribute and you will not be able to access any other attribute. In fact trying so would raise an ActiveRecord::MissingAttributeError error.

 Post.select("content").first.title # => ActiveRecord::MissingAttributeErr...

Help me, there is a zombie process!

Here is a good explanation for zombie processes.

Quote:

If you have zombie processes it means those zombies have not been waited for by their parent (look at PPID displayed by ps -l). 
You have three choices: Fix the parent process (make it wait); kill the parent; or live with it.
Remember that living with it is not so hard because zombies take up little more than one extra line in the output of ps.

On a server I want to get informed if there are zombie processes and track them wi...

Before you make a merge request: Checklist for common mistakes

Merge requests are often rejected for similar reasons.

To avoid this, before you send a merge request, please confirm that your code ...

Subscribe to Rails security mailing list without Google account

The Ruby on Rails security list archive can be found here: http://groups.google.com/group/rubyonrails-security

You can subscribe to this mailing list without a Google account by pasting this URL into your browser (after replacing the email address obviously).

http://groups.google.com/group/rubyonrails-security/boxsubscribe?email=your.name@example.com
                                                                       ^^^^^^^^^^^^^^^^^^^^^ <- Change this