JavaScript: How to log execution times to your browser console

If you are trying to inspect timings in JavaScript, you can use console.time and console.timeEnd which will write to your browser console.

Example:

console.time('lengthy calculation');
lengthyCalculation();
console.timeEnd('lengthy calculation');

lengthy calculation: 1.337ms

Note that this allows using console.timeEnd in another context which is helpful when you are doing things asynchronously, or just in different places.

Works in all browsers, including recent Internet Explorers. For older IEs, you may activate...

Why belongs_to/has_many cannot overwrite methods with the same name

When you use a belongs_to or has_many macro you might be surprised that the methods that it generates does not override a method with the same name. Take this example:

class Project < ActiveRecord::Base
  
  def user
    "foo"
  end
  
  belongs_to :user
  
end

Project.new.user still returns "foo".

The reason for this is that what belongs_to does is actually this:

class Project < ActiveRecord::Base
  include FeatureMethods
  
  def user
    "foo"
  end
  
end

module Project::FeatureMethods

  def user
    # associa...

ActiveRecord 2.3: Nested attribute changes disappear

There is a bug in ActiveRecord 2.3.x that leads to changes in nested forms getting lost.

class Project < ActiveRecord::Base
  has_many :tasks
  accepts_nested_attributes_for :tasks
end

If you access project.tasks after setting tasks through the nested attribute logic, all tasks will be reloaded and all changes will be lost. This usually happens

  • in validations
  • in callbacks
  • after validation errors, when rendering the view again

The attached initializer fixes those issues.

Firefox: Remove dotted border from focused buttons

The following Sass will do the trick:

button,
input[type="reset"],
input[type="button"],
input[type="submit"],
input[type="file"] > input[type="button"]
  &::-moz-focus-inner
    border: none

There's also a plain CSS version.

Note that you can no longer visually navigate through a form with the keyboard without these borders.

Papertrail - Store each models version in a separate table

Store each models version in a separate table

class Post < ActiveRecord::Base
  has_paper_trail :class_name => 'PostVersion'
end

class PostVersion < Version
  # custom behaviour, e.g:
  set_table_name :post_versions
end

Collection of Rails development boosting frameworks

Development environment setup

Rails Composer
: Basically a comprehensive Rails Template. Prepares your development environment and lets you select web server, template engine, unit and integration testing frameworks and more.

Generate an app in minutes using an application template. With all the options you want!

Code generators

Rails Bricks
: A command line wizard. Once you get it running, it creates sleek applications.

RailsBricks enables you to creat...

Bash: Heavy headings for CLI

To print a colored full-width bar on the bash, use this bash script expression:

echo -e '\033[37;44m\nHEADING\033[0m\nLorem ipsum ...'

In Ruby:

  puts "\033[37;44m\n #{text}\033[0m" # blue bar

Notes: -e turns on escape character interpretation for echo. See this card for details on bash formatting.

The line above will print:

Some nifty Rails Rake tasks

Did you know?

rake stats # => LOC per controllers, models, helpers; code ratios, and more
rake notes # => collects TODO, FIXME and other Tags from comments and displays them
rake about # (Rails 3+) => Rails, Ruby, Rake, Rack etc. versions, used middlewares, root dir, etc.

How to force a client-side refresh on a new favicon

Browsers usually cache favicons. If you update the favicon of your web site and want all visitors to see the new icon, you need to give the icon a different URL. You will not have this issue if you cache your assets properly, which appends a fingerprint to your image URL (like favicon.ico?432423432):

<link href="<%= image_path('favicon.ico') %>" rel="icon" type="image/vnd.microsoft.icon">

String#indent: Know your definitions!

String#indent is not a standard Ruby method. When you use it, be sure to know where this method comes from. Many Gems shamelessly define this method for internal usage, and you'll never know when it may be removed (since it's usually not part of the Gem's API).

Unless you're using Rails 4 (which brings String#indent in ActiveSupport), you'll be best of defining it yourself. This card has it for you.

Gems that define String#indent (incomplete)
----------------------------...

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

Debugging in Cucumber

Spreewald includes a few useful steps for debugging a Capybara session.

Then show me the page # => Opens the page in the browser
Then debugger # => Open a debugging session

Cucumber does not find neither env.rb nor step definitions when running features in nested directories

Usually, Cucumber feature files live in features/. When you group them in sub directories, make sure to add -r features to the standard Cucumber options.

In Rails apps, Cucumber options are likely to be stored in config/cucumber.yml.

Cucumber: Wait until CKEditor is loaded

I had to deal with JavaScript Undefined Error while accessing a specific CKEditor instance to fill in text.

Ensure everything is loaded with

patiently do
  page.execute_script("return isCkeditorLoaded('#{selector}');").should be_true
end

Example

The fill in text snippet for Cucumber:

When /^I fill in the "([^\"]+)" WYSIWYG editor with:$/ do |selector, html|
  patiently do
    page.execute_script("return isCkeditorLoaded('#{selector}');").should be_true
  end
  html.gsub!(/\n+/, "") # otherwise: unterminated string lit...

Namespacing: why `uninitialized constant` error may occour in `development` but not in `test` environment

Example:

  class Book::Page
  end
  
  class MyBook < Book
    def new_page
      Page.new # has to be `Book::Page` in development to make it work 
    end
  end

Method new_page may throw an error when it was called during browser interaction in development but doesn't make the test fail.

The reason

Development autoloading isn't smart enough to find the referenced class
At other environments (test, staging, production) autoloading is disabled, that all classes are already loaded when browser interaction takes place what makes...

Howto prompt before accidentally discarding unsaved changes with JavaScript

Ask before leaving an unsaved CKEditor

Vanilla JavaScript way, but removes any other onbeforeunload handlers:

  $(function(){
    document.body.onbeforeunload = function() {
      for(editorName in CKEDITOR.instances) {
        if (CKEDITOR.instances[editorName].checkDirty()) {
          return "Unsaved changes present!"
        }
      }
    }
  }

A robuster implementation example

Note: Don't forget to mark the 'search as you type' forms with the skip_pending_changes_warning class.

var WarnBeforeAccidentallyDiscard...

Make custom web font available within CKEditor content

  1. Make your custom web font available

  2. Add to ckeditor/config.js

    CKEDITOR.editorConfig = function(config) {
      config.contentsCss = [
        '/assets/myCkeditorStyles.css', // any other file to encapsulate custom styles
        '/assets/myFontFaceTags.css'  
      ];
    }
    

It's not enough to provide the font face tags within your public folder. You have to explixitly call it within the ckeditor/config.js.

...