3954 cards

Merging two arbitrary ActiveRecord scopes

Rails 3+ allows you to join two scopes from arbitrary sources by calling the merge method:

scope1 = User.where(:email => 'foo@bar.com')
scope2 = User.where(:first_name => 'hans')
merged_scope = scope1.merge(scope2)

merged_scope.to_a will now trigger a query for the combined scope chain:

SELECT `users`.* FROM `users` WHERE `users`.`email` = 'foo@bar.com' AND `users`.`first_name` = 'hans'

If you are joining two models, you can also merge scopes for different models ([old blog post](https://web.archive.org/web/2018040106...


Gatekeeping: Guide for developer

Note: This process is tailored to our specific needs and tools at makandra Archive . While it will certainly not apply to all (especially larger teams), we think it is a helpful starting point. Compare also the Gatekeeping: Guide for gatekeeper card.

In order to reduce the number of rejects we get from clients, we want to review all code written before it goes to the staging server.

If your project manager wants to do gatekeeping o...

Yarn: if integrity check won't let you start rails console

I ran into a situation in which I received the yarn integrity check warning when starting the rails console even though everything was up to date and correct versions in use.

TLDR: run spring stop

I tried starting the rails console without switching to the correct node version first and received the yarn integrity warning.

warning Integrity check: System parameters don't match                                                                                     
error Integrity check failed                                         ...
Linked contentRepeats

HTTP Status codes for redirecting

Formerly 301 (Moved Permanently) and 302 (Found) were used for redirecting. Browsers did implement them in different ways, so since HTTP 1.1 there are some new status codes which allow for finer distinctions.

The interesting part is how non-GET requests are handled by the redirect. It is preferrable to use the newer status code to avoid unexpected behavior.

303 See Other

The response to the request can be found under another URI using the GET method. When received in response to a POST (or PUT/DELETE), the client should presume that ...


Summarizing heredoc in Ruby and Rails

This card tries to summarize by example the different uses of heredoc.

  • In Ruby << vs. <<- vs. <<~
  • In Rails strip_heredoc vs. squish

strip_heredoc should be used for a text, where you want to preserve newlines. (multi-line -> multi-line)

squish should be used for a text, where you want to squish newlines. (multi-line -> one-line)

Ruby 2.3+

def foo
  bar = <<~TEXT
  puts bar.inspect
foo => "line1\nline2\nline3\n"

Read more: [Unindent HEREDOCs in Ruby 2.3](/makan...

Linked contentRepeats

CSS: Matching against attributes and their values (or parts of them)

You probably know that you can use CSS selectors to match against elements and their attributes, such as:

a[title] { /* any <a> that has a "title" */ }
a[data-fancy="true"] { /* any <a> that has their "data-fancy" attribute set to "true" */ }

But there is more: You do not need to match against "full" attribute values but can match against parts of them.

They work Archive in all somewhat modern browsers, and IE9 or later.

Exact match (CSS2)

[foo="bar"] (matches <div foo="bar" />, but not `<...

Ruby: required keyword arguments in the pre-2.1 era

Starting with Ruby 2.0 you can define methods with keyword arguments.

In 2.1+ required keyword arguments can be defined by using a colon without default value:

def match(value, ignore:)

To accomplish something similar in ruby 1.8, use:

def match(value, options = {})
  ignore = options.fetch(:ignore)

How to avoid raising RestClient exceptions for 4xx or 5xx results

When using RestClient to make an HTTP request, it will raise an exception when receiving a non-successful response.
HTTP status codes like 422 or 403 might be totally expected when talking to APIs, so plastering your code with rescue RestClient::Exception or similar can feel annoying.

It may not be intuitive, but the readme says Archive you can also pass a block to methods like RestClient.get or RestClient::Request.execute. In that case, RestClient will not raise ...

Linked content

Die Grenzen von SEO: was Suchmaschinenoptimierung nicht ist

Der verlinkte Artikel grenzt präzise ab, welche Aufgaben zur Suchmaschinenoptimierung (SEO) gehören und welche nicht.

Suchmaschinenoptimierung ist eine Querschnittsfunktion: die Arbeit vieler unterschiedlicher Abteilungen hat Einfluss auf den SEO-Erfolg der Firma. In diesem Beitrag versuchen wir deswegen, den Kern von SEO zu definieren.


Capybara: Easiest way to get the parent of an element

If you already selected an element and want to get its parent, you can call find(:xpath, '..') on it.
To get the parents parent, call find(:xpath, '../..').


Find a link which contains a twitter icon and check that it links to the correct page:

<a href="http://twitter.com/">
  <i class="icon is-twitter"></i>
link = page.find("a .icon.is-twitter").find(:xpath, '..')
link[:href].should == "http://twitter.com/"

There is a good overview on xpath syntax on [w3schools](https://www.w3schools.com...

Linked contentRepeats

Rails SQL Injection Examples

This page lists many query methods and options in ActiveRecord which do not sanitize raw SQL arguments and are not intended to be called with unsafe user input. Careless use of these methods can open up code to SQL Injection exploits. The examples here do not include SQL injection from known CVEs and are not vulnerabilites themselves, only potential misuses of the methods.

Please use this list as a guide of what not to do.


Don't use migrations to seed default data

Don't insert table rows in a Rails database migration. This will break tests that expect that database to be empty and cause you all sorts of pain.

If you need a place for default application data, use db/seed.rb Archive or put a script into lib/scripts. It won't run automatically, so add a chore story to Pivotal Tracker as a reminder.

Linked contentRepeats

Scrum: Online Planning Poker

If you are using scrum in a project you might be familiar with planning poker, a playful way to agree on story estimates.

PoinZ Archive is an online planning poker app for just that. It's easy to use and does not require registration.

GitHub Actions: Manually running a workflow

To start a workflow manually it must have a trigger called workflow_dispatch:

name: Tests
    - master
    - master
    - master  

In the Actions tab of your repo you can now select a workflow and press "Run Workflow".

See GitHub documentation for details Archive .

GitHub Actions: Retrying a failing step

If you have a flaky command you can use the nick-invision/retry Archive to re-try a failing command, optionally with a timeout:

    - name: Run tests
      uses: nick-invision/retry@v2
        timeout_seconds: 30
        max_attempts: 3
        command: bundle exec rake spec

How to: Ensure proper iconfont rendering with Webpack


After switching a project from Sprockets to Webpack, I started observing a bug that was hard to debug: Our custom icon font could sometimes not be displayed until a full page reload.

Digging deeper the only difference before and after the page load was the encoding interpretation of the iconfont stylesheet:

Correct representation (UTF-8):

.icon:before {
    content: ""

Broken representation (other charset):

Linked contentRepeats

What Ruby’s ||= (Double Pipe / Or Equals) Really Does

It is a common misunderstanding that all [op]=-operators work the same way, but actually they don't.

||= and &&=

Those are special cases, because the assignment will only happen if the first variable passes the check (false or nil for || and true for &&).

a ||= b   # => a || (a = b)
a &&= b   # => a && (a = b)

But still, if reading a has any side effects, they will take place regardless of to what a resolves.

Other [op]=

Assignment will always take place, no matter the value of a.


Custom error pages in Rails

Starting with Rails 3.2, there is a nicer way to display custom error pages (i.e. "page not found") that does not interfere with ExceptionNotifier. (I'm not sure about Airbrake et al.)

José Valim has posted this on his blog Archive , here is a slightly more verbose rundown:

  1. Register your own app as the application responsible for showing error pages by adding

    config.exceptions_app = self.routes

    to your config/application.rb.

  2. Add rout...

This website uses short-lived cookies to improve usability.
Accept or learn more