Rails: Default generators

This is a visualization of the files that will be generated by some useful rails generators. Invoke a generator from command line via rails generate GENERATOR [args] [options]. List all generators (including rails generators) with rails g -h.

generator model migration controller entry in routes.rb views tests
scaffold
resource ✔ ...

ActiveRuby

Looks like ActiveState is trying to market a new Ruby distribution for Enterprises:

ActiveRuby Enterprise Edition is designed for businesses with large Ruby deployments in essential, mission-critical applications that, when down, could cost your business in lost revenue and a damaged reputation. Deploy Ruby with confidence knowing you're using the most secure, enterprise-grade builds for the platforms that power your business. You'll get priority access to our Ruby experts for technical support and best prac...

VCR: Inspecting a request

Using VCR to record communication with remote APIs is a great way to stub requests in tests. However, you may still want to look at the request data like the payload your application sent.

Using WebMock, this is simple: Make your request (which will record/play a VCR cassette), then ask WebMock about it:

expect(WebMock).to have_requested(:post, 'http://example.com').with(body: 'yolo')

Easy peasy.

Related cards

Thinkpad: Disable Bluetooth on start-up

Add the following to /etc/rc.local:

(sleep 3 && echo disable > /proc/acpi/ibm/bluetooth)&

Bluetooth icon will be active for a few seconds, then turn gray.

Some useful vim settings

Below is a list of some VIM settings I find useful. You can add them to your .vimrc.

source $VIMRUNTIME/mswin.vim                 " adds Ctrl-X, Ctrl-C, Ctrl-V; block visual mode is now Ctrl-Q
behave mswin

set autowriteall                             " autosave all files when a buffer is closed

set backupdir=~/.temp                        " dont pollute local directory with swap file, backup files etc
set dir=~/.temp

set undofile                                 " enable persistent undo
set undodir=~/.temp

set encoding=utf-8

...

JavaScript Start-up Performance

As web developers, we know how easy it is to end up with web page bloat. But loading a webpage is much more than shipping bytes down the wire. Once the browser has downloaded our page’s scripts it then has to parse, interpret & run them. In this post, we’ll dive into this phase for JavaScript, why it might be slowing down your app’s start-up & how you can fix it.

The article author also tested 6000+ production sites for load times. Apps became interactive in 8 seconds on desktop (using cable) and 16 seconds on mobile (Moto G4 over 3G).

Never use SET GLOBAL sql_slave_skip_counter with a value higher than 1

If you have a replication error with MySQL and you know the "error" is okay (e.g. you've executed the same statement at the same time on 2 masters which sync each other), you can skip this error and continue with the replication without having to set up the slave from the ground up.

stop slave;
set global sql_slave_skip_counter = 1;
start slave;

But what if you have multiple errors which you want to skip? (e.g. you've executed multiple statement at the same time on 2 masters which sync each other)
Still do not use a value highe...

Error "undefined method last_comment"

This error message may occur when rspec gets loaded by rake, e.g. when you migrate the test database.

NoMethodError: undefined method 'last_comment' for #<Rake::Application:0x0055a617d37ad0>

Rake 11 removes a method that rspec-core < 3.4.4 depends on. To fix, lock Rake to < 11 in your Gemfile:

  gem 'rake', '< 11', # Removes a method that rspec-core < 3.4 depends on

Geordi hints

Reminder of what you can do with Geordi.

Note: If you alias Geordi to something short like g, running commands gets much faster!
Note: You only need to type the first letters of a command to run it, e.g. geordi dep will run the deploy command.

geordi deploy

Guided deployment, including push, merge, switch branches. Does nothing without confirmation.

geordi capistrano

Run something for all Capistrano environments, e.g. geordi cap deploy

geordi setup -t -d staging

When you just clon...

JSONP for Rails

The rack-contrib gem brings a JSONP middleware that just works™. Whenever a JSON request has a callback parameter, it will wrap the application's JSON response appropriately.

The project is a bit dated, but the JSONP middleware is ok.

[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...

How to tackle complex refactorings in big projects

Sometimes huge refactorings or refactoring of core concepts of your application are necessary for being able to meet new requirements or to keep your application maintainable on the long run. Here are some thoughts about how to approach such challenges.

Break it down

Try to break your refactoring down in different parts. Try to make tests green for each part of your refactoring as soon as possible and only move to the next big part if your tests are fixed. It's not a good idea to work for weeks or months and wait for all puzzle pieces ...

JavaScript: Don't throw synchronous exceptions from functions that return a Promise

TLDR: A function is hard to use when it sometimes returns a promise and sometimes throws an exception. When writing an async function, prefer to signal failure by returning a rejected promise.

The full story

When your function returns a promise ("async function"), try not to throw synchronous exceptions when encountering fatal errors.

So avoid this:

function foo(x) {
  if (!x) {
    throw "No x given"
  } else
    return new Promise(funct...

An Introduction to Sending HTML Email for Web Developers

A comprehensive introduction to sending HTML emails.

Intro:

HTML email: Two words that, when combined, brings tears to a developer’s eyes. If you’re a web developer, it’s inevitable that coding an email will be a task that gets dropped in your lap at some time in your career, whether you like it or not. Coding HTML email is old school. Think back to 1999, when we called ourselves “webmasters” and used Frontpage, WYSIWYG editors and tables to mark up our websites.

Table of Contents

  • Introduction To Sending Email Link
  • Email List B...

CarrierWave: When your uploader generates filenames dynamically, use model.save! instead of uploader.recreate_versions!

If your Carrierwave uploader dynamically generates the filename (e.g. by incorporating a user's name), you must call model.save! after recreating versions.

uploader.recreate_versions! does not update the model with the stored filename.

Howto use ActiveRecord preload with plain SQL inner joins

Like you know from "How to tell ActiveRecord how to preload associations (either JOINs or separate queries)", you can tell ActiveRecord explicitly if it should use a LEFT OUTER JOIN or a separate query to preload associations.

Here is some special case, where a simple includes is not possible. For the diagram below we want to sort the rides by the translated name of the departure_place and the arrival_place:

![6020905239052288.png](https://makandracards.com/makandra/43252-howto-combine-custom-sql-with-preload/a...

Debugging cucumber feature with javascript + firefox vnc

TL;DR Debugging problems with javascript errors in cucumber tests is sometimes easier in the browser. Run the test, stop at the problematic point (with Then pause from Spreewald 1.7+) and open VNC for Firefox.

Features:

Howto: Free disk space when /boot is full

Easy mode

This method will remove automatically installed packages that no other packages depend on any more. This, of course, includes obsolete kernel versions, with the explicit exception of the currently running kernel, the kernel version that was installed on the system before that and, of course, the latest updated version of the kernel. However, it will also remove any and all other packages that have been marked as installed automatically but have no other packages depending on them. This could lead to unexpected removal of packag...

Ruby: Writing specs for (partially) memoized code

When you're writing specs for ActiveRecord models that use memoization, a simple #reload will not do:

it 'updates on changes' do
  subject.seat_counts = [5]
  subject.seat_total.should == 5
  # seat_total is either memoized itself, or using some
  # private memoized method
  
  subject.seat_counts = [5, 1]
  subject.seat_total.reload.should == 6 # => Still 5
end

You might be tempted to manually unmemoize any memoized internal method to get #seat_total to update, but that has two disadvant...

Copy to clipboard without flash (clipboard.js)

We used zeroclipboard.js in some of our projects but now we switched to clipboard.js because it does not rely on flash. Flash support of the major browsers has ended.

Some more advantages of clipboard.js:

  • it consists only of a single javascript file, so it does not trigger additional requests with rails
  • it automagically provides user feedback by selecting the text it has copied
  • it provides callbacks for success and error which make it easier to add custom behaviour after copying to the clipboar...

mceachen/closure_tree: Easily and efficiently make your ActiveRecord models support hierarchies

Closure_tree lets your ActiveRecord models act as nodes in a tree data structure.

This promises a few improvements over the battle-tested ancestry gem, such as:

  • Better performance
  • Pre-ordered trees (painful to do with ancestry)
  • Holds a mutex during tree manipulations (an issue with ancestry, where concurrent updates can cause deadlocks and corrupt data).

It has some more moving parts than ancestry though (see below).

Implementation
--------------...

Rails: Talking to the database without instantiating ActiveRecord objects

Instantiating ActiveRecord objects comes expensive. To speed up things, you can choose a more direct way to talk to your database: the ActiveRecord::ConnectionAdapters::DatabaseStatements module.

Using the module and its methods is not suggested in the usual in-app workflow, as validations, callbacks, custom getters/setters etc. are ignored. However, for database-centered stuff like migrations, these fill the gap between writing pure SQL and full...

Nested ActiveRecord transaction pitfalls

When working with custom transactions and use ActiveRecord::Rollback you may encounter unexpected behaviour if you try to roll back your changes.

tl;dr

When using nested transactions, ActiveRecord::Rollback might not do what you expect, since it will only roll back the inner, but not the outer transaction.

You can fix this behavior by using transaction(joinable: false) but this leads to a bunch of different problems.

When you don't need an explicit ActiveRecord::Rollback, don't worry about any of this and just use a plan `tran...

Repeatedly execute a bash command and observe its output

You can have a command repeatedly executed and the output displayed. This is useful e.g. for monitoring file system changes with ls, but has many more applications.
The update frequency is controlled by the -n argument (default: 2s), which is locale-specific; i.e. you might need to use a comma as delimiter.

  > watch -n 1.5 ls