3708 cards
View
Repeats

Obtain pessimistic row locks on ActiveRecord objects

When requests arrive at the application servers simultaneously, weird things can happen. Sometimes, this can also happen if a user double-clicks on a button, for example.

This often leads to problems, as two object instances are modified in parallel maybe by different code and one of the requests writes the results to the database.

In case you want to make sure that only one of the requests "wins", i.e. one of the requests is fully executed and completed while the other one at least has to wait for the first request to be completed, you ha…

Repeats

Hilfe, ich hänge beim Programmieren fest!

Bei makandra bist Du mit Kollegen umgeben, die seit Jahren mit einem ähnlichen Stack entwickeln wie du. Es sollte deswegen nie einen Grund geben, länger allein an einem Programmierproblem festzuhängen.

In diesen drei Schritten kommst du immer und zeitnah zu einer Lösung:

  1. Dein Problem besser kennen lernen
  2. Gute Fragen in #geeks stellen
  3. Eskalation in #sos

Schritt 1: Dein Problem besser kennen lernen

Grenze das Problem ein

Ein erster Schritt bei der Problemsuche ist immer, den Ort im Quelltext einzugrenzen, der das unge…

Best Practice: Creating User Accounts Without Sending the Password

In applications without a sign-up, user accounts are usually created by an admin. This imposes two challenges:

  • How to transmit the password securely and
  • How to make the user change the initial password immediately

There is a simple solution: create the account with a secret password, then ask the user to use the password reset with his user name.

How to avoid ActiveRecord::EnvironmentMismatchError on "rails db:drop"

After loading a staging dump into development, you might get an ActiveRecord::EnvironmentMismatchError when trying to replace the database (like rails db:drop, rails db:schema:load).

$ rails db:drop
rails aborted!
ActiveRecord::EnvironmentMismatchError: You are attempting to modify a database that was last run in `staging` environment.
You are running in `development` environment. If you are sure you want to continue, first set the environment using:

        bin/rails db:environment:set RAILS_ENV=development

Starting with R…

Repeats

Stop writing "require 'spec_helper'" in every spec

Simply add this to your .rspec instead:

--require spec_helper

If you are on rspec >= 3 and use a rails_helper.rb require this instead of the spec_helper:

--require rails_helper

If you are using parallel_tests and this is not working for you, .rspec might be ignored. Try using a .rspec_parallel file.

Linked contentDeprecated

Event order when clicking on touch devices

Touch devices have their own set of events like touchstart or touchmove. Because mobile browsers should also work with with web applications that were build for mouse devices, touch devices also fire classic mouse events like mousedown or click.

When a user follows a link on a touch device, the following events will be fired in sequence:

  • touchstart
  • touchend
  • mousemove
  • mousedown
  • mouseup
  • click

Canceling the event sequence ——————-…

Bash: How to use colors in your tail output

Sometimes it's nice to have some coloring in your logs for better readability. You can output your logs via tail and pipe this through sed to add ANSI color annotations (which your console then interprets).

To print a log (e.g. rails log) and color all lines containing "FATAL" in red and all lines with "INFO" in green:

tail -f /path/to/log | sed --unbuffered -e 's/\(.*INFO.*\)/\o033[32m\1\o033[39m/' -e 's/\(.*FATAL.*\)/\o033[31m\1\o033[39m/'

Here are the …

Capybara: How to find a hidden field by its label

To find an input with the type hidden, you need to specify the type hidden:

find_field('Some label', type: :hidden)

Otherwise you will see an exception :

find_field('Some label')
# => Capybara::ElementNotFound: Unable to find field "Some label" that is not disabled`.

Note: Usually you don't need to check the input of hidden fields in an integration test. But e.g. waiting for a datepicker library to write the expected value to this field before continuing the test, which prevents flaky tests, is a valid use case.

Linked contentAuto-destruct in 36 days

Updated: Using ActiveRecord with threads might use more database connections than you think

Updated the recommendation to always release connections explicititely by calling ActiveRecord::Base.clear_active_connections! right before your thread terminates.

While the Rails 4.2 API docs suggested that connections were released automatically, the current API docs no longer contain this wording.

Quick HTML testing with RubyMine

If you need to test some HTML, e.g. an embed code, you can use RubyMine's "scratch files":

  1. File > New Scratch File (or Ctrl + Shift + Alt + Ins)
  2. Select "HTML" as file type
  3. Write or paste the HTML
  4. Move your mouse to the upper right corner of the scratch file editor. Pick a browser to instantly open your file.
Repeats

ActiveRecord: Specifying conditions on an associated table

We can use ActiveRecord's where to add conditions to a relation. But sometimes our condition is not on the model itself, but on an associated model. This card explains multiple ways to express this condition using ActiveRecord's query interface (without writing SQL).

As an example we will use a User that has many Posts:

```ruby
class User < ApplicationRecord
has_many :posts
scope :active, -> { tra…

Letting a DOM element fade into transparency

You can use the CSS property mask-image to define an "alpha channel" for an element.

E.g. to let an element start at full opacity at the top and gradually fade into transparency at the bottom:

.box {
  -webkit-mask-image: linear-gradient(to bottom, black 0%, transparent 100%)
  mask-image: linear-gradient(to bottom, black 0%, transparent 100%)
}
  • A fully opaque black pixel will render the masked pixel fully opaque
  • A fully transparent black pixel will render the ma…
Repeats

Don't name columns like counter_cache columns

ActiveRecord has a feature called counter caching where the containing record in a has_many relationship caches the number of its children. E.g. when you have House has_many :rooms, Rails can cache the number of rooms in House#rooms_count.

Mind that when a model has a column that looks to Rails like a counter-cache column, Rails will apply counter-cache logic to your model, even if you're not using counter caches.

E.g. you have a house with 12 rooms, but `house.r…

Linked content

Traversing the DOM tree with jQuery

jQuery offers many different methods to move a selection through the DOM tree. These are the most important:

$element.find(selector)
Get the descendants of each element in the current set of matched elements, filtered by a selector. Does not find the current element, even it matches. If you wanted to do that, you need to write $element.find(selector).addBack(selector).
$element.closest(selector)
Get the first ancesto…
Linked contentRepeats

Rails: Overriding view templates under certain conditions only

Rails offers a way to prepend (or append) view paths for the current request. This way, you can make the application use different view templates for just that request.

Example

A use case of this is a different set of view templates that should be used under certain circumstances:

```
class UsersController < ApplicationController

before_action :prepare_views

def index

end

private

def prepare_views
if prepend_view_path Rails.root.join('app', 'views', 'special') end end

end …

Linked contentAuto-destruct in 29 days

Updated: New Gem safe_cookies: Have your cookies as secure and HttpOnly as possible

Card is now deprecated and on auto-destruct.

The gem is no longer maintained, because flagging Secure is irrelevant when using HSTS.

Also, IE11 received HSTS support in 2015 so there is really no reason any more.

Note that security audits may still request Secure cookies. Don't try to discuss the sense of this requirement with them, just [make them happy](https://makandracards.com/makandra/53693-rails-flagging-all…

Ruby: How to fetch a remote host's TLS certificate

TLS/SSL certificates are often used for HTTPS traffic. Occasionally a service may also use their TLS certificate to support public-key encrypting data (e.g. when it is part of the URI and visible to the user, but contains sensitive information).

Here is how to easily fetch such certificate data.

certificate = Net::HTTP.start('example.com', 443, use_ssl: true) { |http| http.peer_cert }
# => #<OpenSSL::X509::Certificate: subject=#<OpenSSL::X509::Name CN=www.example.org,...>

certificate.public_key
# => #<OpenSSL::PKey::RSA:0x...
This website uses cookies to improve usability and analyze traffic.
Accept or learn more