3520 cards
View

Rails: Disabling logging entirely

In an environment:

config.logger = Logger.new('/dev/null')

Capistrano + Rails: Automatically skipping asset compilation when assets have not changed

In medium-sized to large Rails applications, asset compilation can take several minutes. In order to speed up deployment, asset precompilation can be skipped. This card automates the process.

Capistrano 3

```
namespace :deploy do

desc 'Automatically skip asset compile if possible'
task :auto_skip_assets do
asset_locations = %r(^(Gemfile.lock|app/assets|lib/assets|vendor/asset))

revisions = []
on roles :app do
  within current_path do
    revisions << capture(:cat, 'REVISION').strip
  ...
Repeats

How to update a single gem conservatively

The problem

Calling bundle update GEMNAME will update a lot more gems than you think. E.g. when you do this:

bundle update cucumber-rails

… you might think this will only update cucumber-rails. But it actually updates cucumber-rails and all of its dependencies. This will explode in your face when one of these dependencies release a new version with breaking API changes. Which is all the time.

In the example above updating cucumber-rails will give you Capybara 2.0 (because capybara is a dependency of `cucumber-rail…

Repeats

Traverse an ActiveRecord relation along an association

The Edge Rider gem gives your relations a method #traverse_association which
returns a new relation by "pivoting" around a named association.

Say we have a Post model and each Post belongs to an author:

class Post < ActiveRecord::Base
  belongs_to :author
end

To turn a relation of posts into a relation of its authors:

posts = Post.where(:archived => false)
authors = posts.traverse_association(:author)

You can traverse multiple associations in a single call.
E.g. t…

How to add a user with all privileges to MariaDB

Add a user with password

mysql -uroot -p
CREATE USER 'newuser'@'localhost' IDENTIFIED BY 'changeme';
GRANT ALL PRIVILEGES ON * . * TO 'newuser'@'localhost';
FLUSH PRIVILEGES;
exit;

Add a user without password

mysql -uroot -p
CREATE USER 'newuser'@'localhost' IDENTIFIED BY '';
GRANT ALL PRIVILEGES ON * . * TO 'newuser'@'localhost';
FLUSH PRIVILEGES;
exit;

If you don't have a user with the sufficient access rights, follow these steps to reset…

Repeats

Operators "in" and "of" are very inconsistent between CoffeeScript and JavaScript

CoffeeScript and JavaScript (ECMAScript) both have operators in and of. Each language use them for more than one purpose. There is not a single case where the same operator can be used for the same purpose in both languages.

Check if an object (or its prototype) has a property

CoffeeScript

var hasFoo = 'foo' of object

JavaScript

var hasFoo = 'foo' in object;

Iterate through all properties of an object
================================…

Repeats

Printing background color of elements

Browsers' printing methods usually don't print background colors. In most cases this is the desired behavior, because you don't want to spent tons of ink printing the background of a web page. But in some cases you want to print the background color of elements, e.g. bars of a chart. For those elements you need to set the following css styles:

Chrome and Safari:

-webkit-print-color-adjust: exact;

Firefox:

color-adjust: exact;
Repeats

Stretching an HTML page to full height

This card existed before, but was outdated due to browser implementation changes. The information below is validated for the current list of browsers we support.


By default your html and body elements are only as high as the actual page content. If you only have two lines of text in your page, your html and body elements will only be around 40 pixels high, regardless of the size of your browser window.

You might be surprised by this, since setting a background on either html and body does cover the enti…

CSS: Using the current text color for other color properties

There is a kinda secret, yet well supported CSS feature called currentColor. It's like a special CSS variable that has been supported in almost all browsers for almost all time (see linked Caniuse).

Usage

The currentColor value can be used in CSS to indicate the current value of color should be used. A common use case is setting a border color:

a.ghost
  color: white
  border: 1px solid currentColor
  &:hover
    color: red // Border color will change as well 

Note that in many cases, you can simply omit the color to ac…

External contentRepeats

skorks/nesty

Nested exceptions for Ruby:

When you rescue an error and then re-raise your own, you don't have to lose track of what actually occured, you can keep/nest the old error in your own and the stacktrace will reflect the cause of the original error.

This is awesome when you classes convert exception classes. I now always subclass Nesty::NestedStandardError instead of StandardError for my own error classes.

About Exception#cause

Ruby 2.1 has a built-in mechanism with Exception#cause, which serves a similiar purpos…

Repeats

Jasmine: Adding custom matchers

Definition

A matcher is a function that returns an object with a compare key. Usually it is registered with beforeEach:

beforeEach ->
  jasmine.addMatchers
  
    # Example matcher
    toBeAnything: ->
      compare: (actualValue, matcherArguments...) ->
         # Do some computations here ...
         
         # Return whether the actualValue matches the expectation
         pass: true

Usage

expect(actualValue).toBeAnything(matcherArguments...)

When a matcher is invoked, Jasmine will call its compare() fu…

Repeats

Rails route namespacing (in different flavors)

TL;DR There are three dimensions you can control when scoping routes:

scope module: 'module', path: 'path', as: 'as' do
  resources :examples, only: :index
end

=> Path Helpers: as_examples_path and as_examples_url
=> URLs: /path/examples
=> Controller module: Module::ExamplesController and views location: app/views/module/examples/

Changing URLs only

When you want to namespace some paths but leave the corresponding controllers and url helpers unaffected, you can use the scope method like follows:

```
scope path…

Capistrano + Rails: Tagging production deploys

Just like Ruby Gems tag their version releases to the corresponding Git commit, it can be helpful to track production deploys within the commit history. This task does the tagging for you.

Capistrano 3

# lib/capistrano/tasks/deploy.rb
namespace :deploy do
  ...

  desc 'Tag the deployed revision'
  task :tag_revision do
    date = Date.today.to_s

    puts `git tag deploy-#{date} #{fetch :current_revision}`
    puts `git push --tags origin`
  end

end

```
# config/deploy/production.rb
after 'deploy:finished', 'deploy:tag_revi…

Fixing authentication in legacy applications

Authentication is hard: there are many edge cases, and most users (including yourself) usually only go the "happy path" once and never see the edge cases. If you have rolled your own authentication, or been using older authentication solutions, or resorted to HTTP Basic Authentication, this card will tell you what to do to make your application safe.

Any application that stores sensitive data in the browser

That is: cookies, e.g. by offering a login.

  • Ask the admins to [turn on SSL](https://makandracards.com/makandra/1416-integrate-s…
Repeats

Lazy-loading images

Since images are magnitudes larger in file size than text (HTML, CSS, Javascript) is, loading the images of a large web page takes a significant amount of the total load time. When your internet connection is good, this is usually not an issue. However, users with limited bandwidth (i.e. on mobile) need to mine their data budget better.

One popular strategy to improve the website performance is to not load images until they enter the viewport – aka "lazy-loading images".

General Issues

  • Crawlers do not execute JavaScript (generally sp…

How to fix: Rbenv fails to install Ruby 1.8.7 with OpenSSL

Installing ruby 1.8.7 with rbenv might fail if you have installed libssl-dev instead of libssl1.0-dev (default in Ubuntu 18.04).

Run sudo apt install libssl1.0-dev to remove libssl-dev and add libssl1.0-dev.

You can check installed libssl packages using apt list:

```
$ apt list –installed | grep libssl

WARNING: apt does not have a stable CLI interface. Use with caution in scripts.

libssl-dev/bionic,now 1.1.0g-2ubuntu4 amd64 [installed]
libssl-doc/bionic,bionic,now 1.1.0g-2ubuntu4 all [installed,automatic]
libssl1.0.0/bion…

Repeats

Rails: Including HTML in your i18n locales

TL;DR Append your locale keys with _html to have them marked as html_safe.


When you're localizing a Rails application, sometimes there is this urge to include a little HTML. Be it some localized link, or a set of <em> tags, you'd like to have it included in the locale file. Example:

```
# Locale file
en:
page:
text: 'Please visit our corporate website to learn more about the corporation.'

HAML

= t('.text')

Desired output

Please visit our <a href="https://w…

Deprecated

RubyMine: Scratch files

There are times when you have a chunk of text that you want to do something with, e.g. replace something on it, or quickly edit it.

While you can open your favorite non-RubyMine editor for this, there is also a plugin: Scratch.

It allows RubyMine to open temporary files (actually they are saved, but somewhere inside the plugin's directory) so you don't need to switch to a text editor like gEdit that works differently and may not even offer what you are used to.

Note that RubyMine also offers so…

This website uses cookies to improve usability and analyze traffic.
Accept or learn more