Why two Ruby Time objects are not equal, although they appear to be

So you are comparing two Time objects in an RSpec example, and they are not equal, although they look equal:

expected: Tue May 01 21:59:59 UTC 2007,
     got: Tue May 01 21:59:59 UTC 2007 (using ==)

The reason for this is that Time actually tracks fractions of a second, although #to_s doesn't say so and even though you probably only care about seconds. This means that two consecutive calls of probably return two inequal values.

If you only care about second precision you can compare two Times by calling #to_i

External content

travisliu/traim: Resource-oriented microframework for RESTful APIs

Use Traim to build a RESTful API for your ActiveRecord models with very little code.

Traim assumes your API resources will map 1:1 to your ActiveRecord models and database tables. This assumption usually falls apart after a few months into a project, so be ready to replace your Traim API with something more expressive afterwards.

Traim outputs a Rack application which you can either serve standalone or mount into your Rails app.

External content

ActiveRecord: How to use ActiveRecord standalone within a Ruby script

Re-creating a complex ActiveRecord scenario quickly without setting up a full-blown Rails app can come in handy e.g. when trying to replicate a presumed bug in ActiveRecord with a small script.

# Based on

Run this script with $ ruby my_script.rb

require 'sqlite3'
require 'active_record'

Use binding.pry anywhere in this script for easy debugging

require 'pry'

Connect to an in-memory sqlite3 database


ImageMagick: How to auto-crop and/or resize an image into a box


ImageMagick can automatically crop surrounding transparent pixels from an image:

convert input.png -trim +repage output.png

You need to +repage to update the image's canvas, or applications will be randomly confused.
Trimming specific colors is also possible, see the documentation.

Resizing into a box

Occasionally, you want to resize an image to a maximum width or height, and change the "outer" image dimensions to something that won't match the input image.

To re…

Guide: How to use our (maybe in future) default rubocop config

Follow the instructions here.

PRs at makandra/rubocop-config are welcome. Also check the issue tracker.


Since version 2017-1 RubyMine runs cops in the background, and displays RuboCop offenses the same way as it does RubyMine inspections. (…

Know what makes your browser pant

I figure we needed a definitive reference for what work is triggered by changing various CSS properties. It's something I get asked about often enough by developers, and while we can do tests with DevTools, I have both the time and inclination to shortcut that for everyone. I'm nice like that. —Paul Lewis


Rails: When defining scopes with class methods, don't use `self`

Sometimes it is useful to define a named scope by implementing a static method with the scope's name on the scoped class. For instance, when a method should decide which existing scope should be the next link in the scope chain. Take this class for example:

class Meal < ActiveRecord::Base

  named_scope :for_date, lambda { |date| :conditions => { :date => date }}
  named_scope :with_meat, :conditions => { :meat => true }
  named_scope :without_meat, :conditions => { :meat => false }

  def self.suitable_for(user)

Deleting stale Paperclip attachment styles from the server

Sometimes you add Paperclip image styles, sometimes you remove some. In order to only keep the files you actually need, you should remove stale Paperclip styles from your server.

This script has been used in production successfully. Use at your own risk.

# Config #######################################################################
delete_styles = [:gallery, :thumbnail, :whatever]
scope = YourModel # A scope on the class with #has_attached_file
attachment_name = :image # First argument of #has_attached_file
noop …


Browsers will not send a referrer when linking from HTTPS to HTTP

  • When your site is on HTTPS and you are linking or redirecting to a HTTP site, the browser will not send a referrer.
  • This means the target site will see your traffic as "direct traffic", i.e. they cannot distinguish such hits from a user who directly typed in the URL.

Reasons for this behavior

It's probably because of this RFC:

Clients SHOULD NOT include a Referer header field in a (non-secure) HTTP request if the referring page was transferr…


Don't use the || operator to set defaults

I often see the use of || to set a default value for a variable that might be nil, null or undefined.

x = x || 'default-value'

This pattern should be avoided in all languages.

While using || works as intended when x is null or an actual object, it also sets the default value for other falsy values, such as false. false is a non-blank value that you never want to override with a default.

To make it worse, languages like JavaScript or Perl have [many more fal…


Cucumber: Clear localStorage after each scenario

Capybara clears cookies before each scenario, but not other client-side data stores. If your app is using localStorage or sessionStorage, contents will bleed into the next scenario.

Use this hook to remove all site data after each scenario:

After do
  if Capybara.current_driver == :selenium && !Capybara.current_url.starts_with?('data:')
    page.execute_script <<-JAVASCRIPT

ActiveRecord::RecordNotFound errors allow you to query the :name and :id of the model that could not be found

ActiveRecord::RecordNotFound errors provide quite meaningful error messages that can provide some insight on application details. Consider the following:

ActiveRecord::RecordNotFound: Couldn't find Organisation::Membership with 'id'=12 [WHERE "organisation_memberships"."user_id" = 1]

You should probably not simply render those error messages to the user directly. Instead you you might want to re-raise your own errors. ActiveRecord::RecordNotFound provides you with methods :model and :id where you can get information about w…

External content

murdho/rack-cargo: Batch requests for Rack APIs

rack-cargo gives your API a new /batch route that lets clients perform multiple API calls with a single request.

The batched calls are resolved internally and are then returned as an array of responses:

// This is batch request payload:
"requests": [
"name": "order",
"path": "/orders",
"method": "POST",
"body": {
"address": "Home, 12345"
"name": "order_item", …


Fun with Ruby: Returning in blocks "overwrites" outside return values

In a nutshell: return statements inside blocks cause a method's return value to change. This is by design (and probably not even new to you, see below) – but can be a problem, for example for the capture method of Rails.

Consider these methods:

def stuff
  puts 'yielding...'
  puts 'yielded.'

We can call our stuff method with a block to yield. It works like this:

>> stuff { puts 'hi!' }
=> true

So the block is yielded a…

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.


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

RSpec's hash_including matcher does not support nesting

You can not use the hash_including argument matcher with a nested hash:

describe 'user' do
  let(:user) { {id: 1, name: 'Foo', thread: {id: 1, title: 'Bar'} }

  it do 
    expect(user).to match(
        id: 1, thread: {id: 1}

The example will fail and returns a not very helpful error message:

expected {:id => 1, :name => "Foo", :thread => {:id => 1, :title => "Bar"}} to inc…


How to solve Selenium focus issues

Selenium cannot reliably control a browser when its window is not in focus, or when you accidentally interact with the browser frame. This will result in flickering tests, which are "randomly" red and green. In fact, this behavior is not random at all and completely depends on whether or not the browser window had focus at the time.

This card will give you a better understanding of Selenium focus issues, and what you can do to get your test suite stable again.

Preventing accidental interaction with the Selenium window ——————–…

Rails: wrap_parameters for your API

Rails 5 (don't know about the others) comes with an initializer wrap_parameters.rb. Here you can tell rails to wrap parameters send to your controllers for specific formats into a root node which it guesses from the controller name.

ActiveSupport.on_load(:action_controller) do
  wrap_parameters format: [:json]

This would wrap a flat json body, like

{"name": "Konata"}

that gets send to your UsersController into

{"name" => "Konata", "user" => {"name" => "Konata"}}

Note that the params are now duplicat…

3409 cards