View
External contentRepeats

Rails 3+: strip_heredoc (String) - APIdock

Note: If you're on Ruby 2.3+ there's a <<~ operator to automatically unindent HEREDOCs.


Copied from the documentation:


strip_heredoc() public

Strips indentation in heredocs.

For example in

if options[:usage]
  puts <<-USAGE.strip_heredoc
    This command does such and such.

    Supported options are:
      -h         This message
      ...
  USAGE
end

the user…

Chrome: Making high-resolution website screenshots without add-ons

If you want to make a screenshot of a website that works well in print or on a high-DPI screen (like Apple Retina displays), here is how you can capture a high-resolution screenshot.

If you have multiple screens, you can do this without an addon:

  • Open the website
  • Resize the Chrome window so it covers multiple monitors (in Linux you can hold ALT and resize by dragging with the right mouse button)
  • Zoom into the page using CTRL + and CTRL - so it covers most of the window area. Leave generous padding on the left and right so it look…
Repeats

Heads up! Years are always floats in Rails < 4

Watch out when saying something like 1.year in Rails. The result is not a Fixnum and can cause unexpected errors when the receiving end expects a Fixnum.

While anything from seconds to months are Fixnums, a year is a Float in Rails – when called on a Fixnum itself:

>> 10.seconds.class
=> Fixnum
>> 2.minutes.class
=> Fixnum
>> 24.hours.class
=> Fixnum
>> 28.days.class
=> Fixnum
>> 9.months.class
=> Fixnum
>> 1.year.class
=> Float # Boom.

While they are [technically correct](http:…

Katapult 0.4.0 released

Features

  • Generating a project README
  • Finally: Support for modelling associations between models in your application model! Example:
# lib/katapult/application_model.rb

model 'Cart' do |cart|
  cart.belongs_to 'User'
end

crud 'User' do |user|
  user.attr :fullname
end

Cucumber: How to avoid VCR errors for unused requests in pending tests

When you have a pending Cucumber step (or feature) that also uses an existing VCR cassette, your pending test may fail at the very end with an error like this:

There are unused HTTP interactions left in the cassette:
  - [get ...] => [200 ...]
  - [get ...] => [200 ...] (VCR::Errors::UnusedHTTPInteractionError)

The error happens because your VCR is configured to complain about cassettes that contain extra requests which your test did not use. This is often a good configuration.
If you do not want to change your whole test suite…

How to mirror a git repo to a new remote

Say you want to move a git repository from one remote (perhaps Github) to another (perhaps Gitlab).

If you have the repo checked out, you still should make sure to mirror all branches of the old remote, not only those you happen to have checked our. Otherwise the target repo will become a copy of your current repo, and not the source repo, potentially missing commits. You can use this:

```
git rename origin old-origin
git remote add origin git fetch old-origin --prune git push --prune origin +refs/remotes/old-origin/*:refs/hea...

Repeats

CSS: Opacity is not inherited in Internet Explorer

Elements will not inherit their parent's opacity in IE for no good reason. This can lead to unexpected behaviour when you want to fade/hide an element and all its children.

To fix it, give the element defining the opacity a non-static positioning. For example:

.foo {
  opacity: 0.2;
  position: relative; // for IE
}

While the linked article describes this problem for IE9 and below, I have encountered the same issue in IE10 and IE11.

Just go away, Internet Explorer!

RSpec expects pending tests to fail

When flagging a spec that will be implemented later as pending, include a failing spec body or RSpec 3 will consider the pending test as failing.

The reasoning is: If the spec is flagged as pending but passes, it should not be pending. So these will fail:

it 'does something' do
  pending
end

it 'does something else' do
  pending
  expect(1).to eq(1)
end

The first case may be unexpected, if you just wanted to write down that something should eventually happen that will be implemented later.

Instead, …

Repeats

Centering with CSS vertically and horizontally (all options overview)

There are a million ways to center <div>s or text in CSS, horizontally or vertically. All the ways are unsatisfying in their own unique way, or have restrictions regarding browser support, element sizes, etc.

Here are two great resources for finding the best way of aligning something given your use case and browser support requirements:

How to center in CSS
A long form that lets you define your use case and browser support requirements, then shows you the preferred way of aligning.

[Centering CSS: A com…

Decide whether cronjobs should run on one or all servers

Understanding your type of cronjob

Some cronjobs must only run on a single server. E.g. when you run nightly batch operations on the database, it should probably run on a single server. Running it on multiple servers would likely result in deadlocks or corrupt data.

Some cronjobs must always run on all servers. E.g. starting a sidekiq process on reboot.

Configuring whenever

If not configured otherwise, cronjobs defined in whenever's `s…

Katapult 0.3.0 released

Katapult 0.3.0 brings Rails 5 and Ruby 2.5 support with a new design, plus a ton of smaller features, fixes and improvements.

Features

  • Generating a Rails 5.1.4 app on Ruby 2.5.0
  • Dropped asset pipeline in favor of Webpacker
  • The generated application now has a sleek, simple design based on Bootstrap
  • Employing Unpoly
  • New application model DSL shortcut crud for "create a model and a web UI with crud actions"
  • The generated application model is now a transformable e…
Auto-destruct in 46 days

Unpoly now has an e-mail group

Unpoly has an e-mail group to discuss Unpoly and to get notified of new releases.

If you want to stay up to date with the latest changes, you should join it.

Repeats

Testing ActiveRecord validations with RSpec

Validations should be covered by a model's spec.

Recipe for testing any validation

In general any validation test for an attribute :attribute_being_tested looks like this:

  1. Make a model instance (named record below)
  2. Run validations by saying record.valid?
  3. Check if record.errors[:attribute_being_tested] contains the expected validation error
  4. Put the attribute into a valid state
  5. Run validations again by saying record.valid?
  6. Check if record.errors[:attribute_being_tested] does *…

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 "…

Think twice before using application names in your variables and methods

I recently had fun with replacing a custom video plattform ("mycustomtv") in one of our applications. I learned a lot about naming stuff.

youtube_mycustomtv_chooser is a bad name for a directive.

Why?

  • if you add, for example, other video systems like vimeo, the name of the method either lies or will get longer.
  • if you replace one system, you will have to change the method and all of its occurrences (and you're very lucky if it is only one poorly named thing in your application)

What would be a better solution?

Abstract fro…

Configuring RubyGems to not install documentation by default

When installing gems, a lot of time is spent building locally installed documentation that you probably never use.

We recommend you disable documentation generation for gem install by default.
Note that Bundler won't install documentation, so this advice applies only when installing gems manually.

If you don't already have it, create a ~/.gemrc file. The gemrc is a Yaml file, so add the following line to add default switches to the gem command.

gem: --no-document

(If you do n…

Ruby: Using all? with empty collection

Enumerable#all? returns true for an empty collection. This totally makes sense but you have to think about it when making assumptions on relations which might be empty.

[].all?(&:will_never_be_called_here) => true

Example with empty collection

class Researcher < ActiveRecord::Base
  has_many :papers
end

class Paper
  validates :topic, inclusion: { in: ['computer_science', 'mathematics', 'economy'] }
end

Easy goal: Delete all researches who write onl…

How to: Run webpack dev server with vcap.me

If your Rails application is using Webpack you need to serve assets on the same host as you application runs, otherwise you will see the following errors in your browser console:

[WDS] Disconnected!
Invalid Host header

So if you are using awesome.vcap.me:3000 you need to start the webpack-dev-server with a different host than localhost (0.0.0.0):

bin/webpack-dev-server --host awesome.vcap.me
View
3421 cards