Different behavior for BigDecimal#floor in Ruby 1.8 and Ruby 1.9

Ruby 1.8 (supplied by Rails' ActiveSupport)

>> BigDecimal.new("0.1").floor.class
=> BigDecimal

Ruby 1.9 (supplied by Ruby 1.9 itself)

>> BigDecimal.new("0.1").floor.class
=> Fixnum

In fact, Float#floor has changed from Ruby1.8 to Ruby 1.9 which is used by BigDecimal#floor internally.

Attached initializer backports Ruby 1.9 behavior to Ruby 1.8.

Fix when assigning nested attributes raises "undefined method `to_sym' for nil:NilClass"

You might have a table without a primary key set in MySQL.

You can fix this by adding a primary key index to the guilty MySQL table, or by setting self.primary_key = "id" in your class definition.

Related, but different issue: Rails 2 does not find an association when it is named with a string instead of a symbol

Customize path for Capybara "show me the page" files

When you regularly make use of Cucumber's "show me the page" step (or let pages pop up as errors occur), the capybara-20120326132013.html files will clutter up your Rails root directory.

To tell Capybara where it should save those files instead, put this into features/support/env.rb:

Capybara.save_and_open_page_path = 'tmp/capybara'

Why your Cucumber feature loses cookies when run under Selenium

When your Cucumber feature seems to forget cookies / sessions when you run it with Selenium check if the test travels in time like here:

Given the date is 2017-10-20
When I sign in
Then I should see "Welcome!"

What happens here is that the Rails application serving pages runs in 2017, but the process running your browser still lives today. This huge gap in time will expire most cookies immediately.

If all you need is to freeze the time to a date, a workaround is to travel to the future instead.

XHR is not JSON

When a Rails controller action should handle both HTML and JSON responses, do not use request.xhr? to decide that. Use respond_to.

I've too often seen code like this:

def show
  # ...
  if request.xhr?
    render json: @user.as_json
  else
     # renders default HTML view
  end
end

This is just plain wrong. Web browsers often fetch JSON via XHR, but they (should) also send the correct Accept HTTP header to tell the server the data they expect to receive.

If you say request.xhr? as a means for "wants JSON" you are ...

Refile: Ruby file uploads, take 3

Jonas Nicklas, the author of Carrierwave and Capybara, has released Refile, a gem for handling file uploads in Rails. It handles direct uploads (also direct uploads to Amazon S3) better than Carrierwave.

The story and reasoning behind some of the decisions in Refile, and how it's different from Carrierwave, by the author himself, is a good read before deciding which way you'll go.

Big Caveat: Refile only stores the original image and r...

Look up a gem's version history

Sometimes it might be helpful to have a version history for a gem, e.g. when you want to see if there is a newer Rails 2 version of your currently used gem.

At first you should search your gem at RubyGems. Example: will_paginate version history.

The "Tags" tab at GitHub might be helpful as well.

Git error: "badTimezone: invalid author/committer line - bad time zone"

You might get the above error message when cloning certain git repositories (for example the rails repository). It indicates that there is a malformed timestamp in some commit, and your git installation is configured to validate it.

As a workaround, you can disable the validation using

git config --global fetch.fsckobjects false

This settings seems to be the default for most git installations anyways.

RSpec: Change the type of a spec regardless of the folder it lives in

In a Rails application, *_spec.rb files get special treatment depending on the file's directory. E.g. when you put a spec in spec/controllers your examples will have some magic context like controller, post or get that appears out of nowhere.

If you want that magic context for a spec in another folder, use the :type option:

describe CakesController, :type => :controller do
  ...
end

Fixing "uninitialized constant ActiveSupport::Dependencies::Mutex (NameError)"

RubyGems 1.6.0 has undergone some changes which may cause Rails 2.x applications to break with an error like this one (e.g. when running script/server):
/usr/lib/ruby/gems/1.8/gems/activesupport-2.3.8/lib/active_support/dependencies.rb:55: uninitialized constant ActiveSupport::Dependencies::Mutex (NameError)

Fix it by adding the following not only to your environment.rb but also into your script/server file, in both cases before boot.rb is required.
require 'thread'

If you still get the error above you can also add `require 'thre...

Inspecting model callback chains

If you need to look at the list of methods that are called upon certain events (like before/after saving etc), do this:

Model._save_callbacks.select {|cb| cb.kind == :before}.map{ |c| c.instance_variable_get :@filter }

Rails 2

User.after_save_callback_chain

To look at the method names only, you could do something like that:

User.after_save_callback_chain.collect(&:method)

Why your previous developer was terrible

When you, as a developer, look at the choices used to build a particular application, you’re blown away at the poor decisions made at every turn. “Why, oh why, is this built with Rails when Node.js would be so much better?” or “how could the previous developer not have forseen that the database would need referential integrity when they chose MongoDB?” But what you may not realize is that you are seeing the application as it exists today. When the previous developer (or team) had to develop it, they had to deal with a LOT of unknowns. They...

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.

Understand ActiveRecord::ReadOnlyRecord error

When you load a record with find options that have SQL fragments in :select or :joins, ActiveRecord will make that record read-only. This is a protective measure by Rails because such a record might have some additional attributes that don't correspond to actual table columns.

You can override that precaution by appending :readonly => false to affected find options or scope options.

Fix AssociationTypeMismatch

When you're getting this error, one possibility is that you've created a select field for an association instead of the associated object's id. Example:

form.select :unit, Unit.for_select

will be expected to deliver a real Unit object, whereas

form.select :unit_id, Unit.for_select

will make Rails typecast the String value from the select field to the unit's ID.

stefankroes's ancestry at master - GitHub

Ancestry is a gem/plugin that allows the records of a Ruby on Rails ActiveRecord model to be organised as a tree structure (or hierarchy). It uses a single, intuitively formatted database column, using a variation on the materialised path pattern. It exposes all the standard tree structure relations (ancestors, parent, root, children, siblings, descendants) and all of them can be fetched in a single sql query. Additional features are STI support, named_scopes, depth caching, depth constraints, easy migration from older plugins/gems, integrit...

How Exchange handles multipart/alternative emails

In Rails, you can very easily send emails with HTML and plaintext bodies.

However, if you're trying to debug those using your normal email account, you might be out of luck: For some reason, Exchange servers will simply throw away the plaintext part of your mail, and just save the html part.

Ruby: How to update all values of a Hash

There are many solutions, but a very concise one is this:

hash.merge!(hash) do |key, old_value, new_value|
  # Return something
end

The block of merge! will be called whenever a key in the argument hash already exists in the base hash. Since hash is updated with itself, each key will conflict and thus allow you to modify the value of each key to whatever you like (by returning old_value you'd get the behavior of Rails' reverse_merge!, by re...

IRB: last return value

In the ruby shell (IRB) and rails console the return value of the previous command is saved in _ (underscore). This might come in handy if you forgot to save the value to a variable and further want to use it.

Example:

irb(main):001:0> 1 + 2
=> 3
irb(main):002:0> _
=> 3
irb(main):003:0> a = _
=> 3

YAML syntax compared with Ruby syntax

yaml4r is a juxtaposition of yaml documents and their Ruby couterpart. Thus, it does a great job as YAML-doc, e.g. when writing Rails locale files. Did you know that ...

  • << is a merge key (similar to & in SASS)
  • there are variables, called aliases. Definition: &alias Some content, usage: *alias.

Caveats

Specifying a key twice does not merge the sub keys, but override the first definition, e.g.

de:
  car: # overridden
    door: Tür
 ...

Login forms: Disable browser prompt to remember the password

In order to prevent the browser from asking whether to remember the password, give a form an autocomplete attribute with the value off:

<form "/session" method="post" autocomplete="off">
  ...
</form>

Rails example

form_for @model, :html => { :autocomplete => "off" } do |form|

"rake gettext:findpo" running forever

Under certain circumstances gettext_i18n_rails will hit a near-infinite loop. This occured in Rails 2.3.5 with Haml 3.0.18 and fast_gettext 0.5.10.

gettext_i18n_rails's Haml-Parser compiles the Haml code and delegates the parsing to ruby_parser. Unfortunately, ruby_parser appears to be confused when a string contains both escaped chars (that is, any unicode characters as ndash, umlauts etc.) and #{} blocks, which makes it extremely slow.

The easiest "solution" we came up with was to replace all occurrences of UTF-8 chars wi...

[jruby] TruffleRuby Status, start of 2017

TruffleRuby is an experimental Ruby implementation that tries to achieve ~10x performance over MRI.

This has been on our radar for a while. They seem to have made significant progress running Rails, reducing start-up time and becoming runtime-independent of the JVM.

Also see [Running Optcarrot, a Ruby NES emulator, at 150 fps with the GUI!](https://eregon.me/blog/2016/11/28/optcarrot.htm...

The asset pipeline does not like files that look like fingerprints

If you have a file that looks like a precompilation fingerprint, the Rails asset pipeline will not see it. So don't have filenames like this:

8e21264d-f678-4005-b90c-8d8288a0d179.ttf