View
Repeats

Ruby: Do not mix optional and keyword arguments

Writing ruby methods that accept both optional and keyword arguments is dangerous and should be avoided.

Consider the following method

def colored_p(object = nil, color: 'red')
  switch_color_to(color)
  puts object.inspect
end


colored_p(['an array'])                   # ['an array'] (in red)
colored_p({ a: 'hash' }, color: 'blue')   # {:a=>'hash'} (in blue)
colored_p({ a: 'hash' })                  # ArgumentError: unknown keyword: a

What happened?

Ruby does not know whether to interpret this as

colored_p({ a: 'hash' }, c...

Solved: Element inside overflow:scroll container cannot be scrolled on iOS when dragged by a contained iframe

Imagine the following HTML structure, where the scrolling container has overflow-y: scroll:

+--scrolling container+-+
|                       |
| +-child element+----+ |
| | ++iframe++        | |
| | |        |        | |
| | |        |        | |
+-----------------------+
  | |        |        |   <-- actually cut off by
  | +--------+        |   <-- scrolling container
  +-------------------+

The issue: On iOS, the child element cannot be scrolled when grabbing the iframe (i.e. putting your finger somewhere on the iframe). …

How to disable Chrome's save password bubble for Selenium tests

When filling out forms in Selenium tests, Chrome shows the (usual) bubble, asking to store those credentials.

While the bubble does not interfere with tests, it is annoying when debugging tests. Here are two ways to disable it:

Option 1: prefs

You can set profile preferences to disable the password manager like so:

prefs = {
  'credentials_enable_service' => false,
  'profile.password_manager_enabled' => false
}

Capybara::Selenium::Driver.new(app, browser: :chrome, prefs: prefs)

Sadly, there are no command line s…

External content

image-to-DataURI converter: Duri.me

Small web application where you can upload an image (PNG, JPEG, GIF) and generate a base64-encoded version of it.

You can copy the result as
- HTML <img> tag with data URI,
- CSS rule with background-image and data URI,
- plain Base64-encoded data URI string.

How to make http/https requests yourself with nc/telnet/openssl

Sometimes you want/have to send specific http(s) requests. You can do that easy with curl or just write the request yourself.

make a http request with nc

nc example.com 80
GET / HTTP/1.1
Host: example.com
# press enter

make a http request with telnet

telnet example.com 80
GET / HTTP/1.1
Host: example.com
# press enter

make https request with openssl

openssl s_client -connect example.com:443
GET / HTTP/1.1
Host: example.com
# press enter

You can specify more headers if you want:

```
nc example.c…

Repeats

Capybara/Selenium: evaluate_script might freeze your browser, use execute_script

In a nutshell: Do not use evaluate_script. Use execute_script instead!


Capybara gives you two different methods for executing Javascript:

page.evaluate_script("$('input').focus()")
page.execute_script("$('input').focus()")

While you can use both, the first line (with evaluate_script) might freeze your Firefox window for 10 seconds.

The reason is that evaluate_script will always return a result. The return value will be converted back to Ruby objects, which in case of complex objects (e.g. a jQuery collection) is *ver…

Repeats

Z-index: About stacking contexts

The z-index CSS styling option is not as "global" as you might believe. Actually, it is scoped to a so-called "stacking context".

The linked article explains what's going on in the internals. Study this example graphic for a quick understanding of the wtf:

Example

It is important to note that DIV #4, DIV #5 and DIV #6 are children of DIV #3, so stacking of those elements is completely resolved within DIV #3. Once stacking and rendering wi…

Rendering 404s for missing images via Rails routes

When you load a dump for development, records may reference images that are not available on your machine.

Requests to those images may end up on your application, e.g. if a catch-all route is defined that leads to a controller doing some heavy lifting. On pages with lots of missing images, this slows down development response times.

You can fix that by defining a Rails route like this:

if Rails.env.development?
  scope format: true, constraints: { format: /jpg|png|gif/ } do
    get '/*anything', to: proc { [404, {}, ['']] }  ...
Repeats

Whitelist Carrierwave attributes correctly

Say you have a User with a Carrierwave attribute #avatar:

class User < ActiveRecord::Base
  mount_uploader :avatar, AvatarUploader
end

When whitelisting the avatar field in the controller, you might do this:

  params[:user].slice(:avatar)

But you probably want this:

  params[:user].slice(:avatar, :avatar_cache, :remove_avatar)

In this example:

  • :avatar_cache allows a newly upload image to persist through form roundtrips in the case of validation errors (something that isn't possible with Papercl…
Repeats

CSS: Don't target multiple vendor-prefixed pseudo-elements in a single rule

Some pseudo-elements need to be addressed with vendor prefixes. E.g. ::selection is not supported by Firefox, you need to use ::-moz-selection instead.

What you cannot do is to define a single CSS rule to address both the standard and vendor-prefixed form:

::selection, ::-moz-selection {
  background-color: red;
}

This rule will be ignored by all browsers. The reason is that if a browser doe…

Sending errors to sentry from development

For the initial setup or changes in the sentry reporting it might be useful to enabled reporting of sentry in development. Don't commit these changes and prefer to report to the staging environment. As other developers might be confused of these errors try to given them a proper message and delete them afterwards.


  1. Add config.raven_dsn = 'your-dns' in config/environments/development.rb.
  2. Add development to existing environments in the Raven.configure block: config.environments = ['development', 'staging', 'production'].
External contentRepeats

Ag: Very fast grep replacement

Ag (aka "the silver searcher") is a very fast replacement for grep.

It will parse your .gitignore for additional speedup. To ignore even more files (node_modules, *.min.js etc), add an .agignore with syntax identical to .gitignore.

On Ubuntu 14.04, don't install via apt-get, but build from source to get a current version.

See Faster Grepping in Vim for hints about vim integration.

Repeats

Manipulate color with Sass functions

Sass comes with many built-in functions to manipulate color. Some of the more interesting functions include:

adjust-hue($color, $degrees)
Changes the hue of a color.
lighten($color, $amount)
Makes a color lighter.
darken($color, $amount)
Makes a color darker.
saturate($color, $amount)
Makes a color more saturated.
desaturate($color, $amount)
Makes a color less saturated.
grayscale($color)
Converts a color to grayscale.
complement($color)
Return…
Repeats

RubyMine users: you should be using bookmarks

RubyMine allows bookmarking lines of code. This is super-helpful when working on a complex problem.
I've been using this feature for a few years now, and so should you! :)

Here are the default Linux/Windows keystrokes. See the documentation for other keybindings.

Add an anonymous bookmark

F11

A gray checkmark will be shown in the gutter on the left.
If you press F11 again on a bookmarked line, the bookmark will be removed.

Add a named bookmark ("mnemonic")

Ctrl

Repeats

Write custom RSpec matchers

There are three ways to define your own RSpec matchers, with increasing complexibility and options:

1) Use RSpec::Matchers.define

RSpec::Matchers.define :be_a_multiple_of do |expected|
  match do |actual|
    actual % expected == 0
  end
  
  # optional
  failure_message_for_should do |actual|
    "expected that #{actual} would be a multiple of #{expected}"
  end
  
  # optional
  failure_message_for_should_not do |actual|
    "expected that #{actual} would not be a multiple of #{expected}"
  end
end

Th…

Repeats

Sass: Do not use comments between selector definitions

Sass lets you easily specify multiple selectors at once like this:

.some-block
  &.has-hover,
  &:hover
    outline: 1px solid red

This will add a red outline on either real hover or when the has-hover class is present. However, adding a comment will void the definition of that line:

.some-block
  &.has-hover, // From hoverable.js <-- DON'T
  &:hover
    outline: 1px solid red

… will simply drop the &.has-hover part.

External contentRepeats

The developer console can do more than you think!

You can do so much more than console.log(...)! See the attached link for a great breakdown of what the developer console can give you.

Some of my favorites:

console.log takes many arguments

E.g. console.log("Current string:", string, "Current number:", 12)

E.g. console.log("Check out the current %o, it's great", location)

[Di…

How to view Image Metadata on the Linux Command Line with ImageMagick

ImageMagick has a command line tool called identify which can read image metadata:

```
>identify -verbose DSC00136.JPG
Image: DSC00136.JPG
Format: JPEG (Joint Photographic Experts Group JFIF format)
Class: DirectClass
Geometry: 5472x3648+0+0
Resolution: 350x350
Print size: 15.6343x10.4229
Units: PixelsPerInch
Type: TrueColor
Endianess: Undefined
Colorspace: sRGB
Depth: 8-bit
Channel depth:
red: 8-bit
green: 8-bit
blue: 8-bit
Channel statistics:
Red:
min: 0 (0)
max: 255 (1)
mean: 11…

View
3311 cards