RSpec: Expect one of multiple matchers to match
RSpec let's you chain a matcher with .or
. The expectation will then pass if at least one matcher matches:
expect(color).to eq("red").or eq("green")
Real-world example
A real-world use case would be to test if the current page has a button with the label "Foo". There are many ways to render a button with CSS:
<input type="button" value="Foo">
<input type="submit" value="Foo">
<button>Foo</button>
We cannot express it with a single have_css()
matcher, since we need the { text: 'Foo' }
optio...
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 spend 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:
-webkit-print-color-adjust: exact; /* Chrome and Safari */
color-adjust: exact; /* Firefox */
Another case is printing of white text. When removing background colors, chances are white text n...
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
...
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...
Carrierwave: Built-in RSpec matchers
CarrierWave comes with some RSpec matchers which will make testing more comfortable. Let's say you have an Uploader like this:
class MyUploader < CarrierWave::Uploader::Base
include CarrierWave::MiniMagick
# Create different versions of your uploaded files:
version :small do
process resize_to_fill: [100, 100]
end
version :medium do
process resize_to_fit: [200, nil]
end
version :large do
process resize_to_limit: [400, 400]
end
end
Imagine you have a class Movie
with an attribute poster
. In ...
Rails: How to provide a public link in a mail
Lets say we have a user
with a contract
whereas contract
is a mounted carrierwave file.
Now we want to send the link to the contract in a mail. For this use case join the root_url
with the public contract path in the mailer view:
Plain text email
URI.join(root_url, @user.contract.url)
HTML email
link_to('Show contract', URI.join(root_url, @user.contract.url).to_s)
Note: You need to follow [http://guides.rubyonrails.org/action_mailer_basics.html#g...
Generating test images on the fly via JavaScript or Ruby
When you need test images, instead of using services like lorempixel or placehold.it you may generate test images yourself.
Here we build a simple SVG image and wrap it into a data:
URI. All browsers support SVG, and you can easily adjust it yourself.
Simply set it as an image's src
attribute.
JavaScript
Simple solution in modern JavaScript, e.g. for use in the client's browser:
function svgUri(text) {
let svg = `
<svg wid...
How to resize your boot partition when there is an encrypted partition after it
Boot partitions from installations prior to the 16.04 era are terribly small. When you install updates and encounter errors due to a full /boot
partition, consider risizing it.
If you can't do the steps described below, ask someone experienced to help you out.
This has worked 100% so far. 1 out of 1 tries. ;)
Scenario A: There is unassigned space on your physical drive
When there is some unpartitioned space on your drive, increasing the size of /boot
is actually very easy (even though the list below is rather long). It only takes a...
Writing strings as Carrierwave uploads
When you have string contents (e.g. a generated binary stream, or data from a remote source) that you want to store as a file using Carrierwave, here is a simple solution.
While you could write your string to a file and pass that file to Carrierwave, why even bother? You already have your string (or stream).
However, a plain StringIO object will not work for Carrierwave's ActiveRecord integration:
>> Attachment.create!(file: StringIO.new(contents))
TypeError: no implicit conversion of nil into String
This is because Carrierwav...
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.
You can do this without an addon:
- Open the website
- If you have multiple monitoros:
- 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 +
andCTRL -
so it covers most of the window area. Leave a little padding on the left and right so...
Capybara: A step for finding images with filename and extension
This cucumber step is useful for testing an image (looking at the src
of the image).
Then(/^I should see the image "([^"]*)"$/) do |filename_with_extension|
expect(page).to have_css("img[src*='#{filename_with_extension}']")
end
Then I should see the image "placeholder.png"
Outline: Read more about how to test a uploaded file here, e.g. file downloads.
Carrierwave: Deleting files outside of forms
TL;DR Use user.update!(remove_avatar: true)
to delete attachments outside of forms. This will have the same behavior as if you were in a form.
As you know, Carrierwave file attachments work by mounting an Uploader
class to an attribute of the model. Though the database field holds the file name as string, calling the attribute will always return the uploader, no matter if a file is attached or not. (Side note: use #present?
on the uploader to check if the file exists.)
class User < ApplicationRecord
mount :avatar, ...
CSS: Giving text lines a background-color (with configurable line padding and margin)
The gist is:
- wrap the text with a
span
- use
line-height
for the spacing between lines ("margin") - use
box-shadow
to control the line background size ("padding")
Example
span
box-shadow: 0 0 0 10px #fff
background-color: #fff
box-decoration-break: clone # Fix Firefox
line-height: 2.2
→ [jsfiddle](https://jsfiddle.net/2fmqgbh...
Spreewald: Content-Disposition not set when testing a download's filename
Precondition
- You are not using javascript tests
- The file is served from a public folder (not via controller)
Problem description
If you deliver files from a public folder it might be that the Content-Disposition
header is not set. That's why the following spreewald step might raise an error:
Then I should get a download with filename "..."
expected: /filename="some.pdf"$/
got: nil (using =~) (RSpec::Expectations::ExpectationNotMetError)
Solution
One solution...
Async control flow in JavaScript: Promises, Microtasks, async/await
Slides for Henning's talk on Sep 21st 2017.
Understanding sync vs. async control flow
Talking to synchronous (or "blocking") API
print('script start')
html = get('/foo')
print(html)
print('script end')
Script outputs 'script start'
, (long delay), '<html>...</html>'
, 'script end'
.
Talking to asynchronous (or "evented") API
print('script start')
get('foo', done: function(html) {
print(html)
})
print('script end')
Script outputs 'script start'
, 'script end'
, (long ...
How to move all files in a folder to a new subfolder
Let's say you have a folder images
and want to to move all files in there to a new subfolder public
.
cd images
mkdir public
mv !(public) public
The !(public)
excludes the new subfolder itself from being moved.
A Theme Switcher
Hack to implement an inverted "night mode" theme with a few lines of CSS.
Colors in images are preserved.
Vagrant: create entry for box in .ssh/config
If you want to ssh into your vagrant box without switching into the project directory and typing vagrant ssh
, you can also create an entry directly in ~/.ssh/config
. This will allow you to use ssh <my-box>
from anywhere. Simply paste the information provided by vagrant ssh-config
to your ~/.ssh/config
-File: vagrant ssh-config >> ~/.ssh/config
Example:
$ vagrant ssh-config
Host foobar-dev
HostName 127.0.0.1
User vagrant
Port 2200
UserKnownHostsFile /dev/null
StrictHostKeyChecking no
PasswordAuthentication no
Id...
Deleting stale Paperclip attachment styles from the server
Sometimes you add Paperclip image styles, sometimes you remove some. In order to only keep the files you actually need, you should remove stale Paperclip styles from your server.
This script has been used in production successfully. Use at your own risk.
# Config #######################################################################
delete_styles = [:gallery, :thumbnail, :whatever]
scope = YourModel # A scope on the class with #has_attached_file
attachment_name = :image # First argument of #has_attached_file
noop ...
ImageMagick: How to auto-crop and/or resize an image into a box
Auto-cropping
ImageMagick can automatically crop surrounding transparent pixels from an image:
convert input.png -trim +repage output.png
You need to +repage
to update the image's canvas, or applications will be randomly confused.
Trimming specific colors is also possible, see the documentation.
Resizing into a box
Occasionally, you want to resize an image to a maximum width or height, and change the "outer" image dimensions to something that won't match the input image.
To re...
Caution: Carrierwave has your file three times (temporarily)
When storing a file with Carrierwave, it is always cached prior to actually storing it (to support form roundtrips).
Carrierwave by default 1) copies the file to the cache and then 2) copies it again to its final destination (deleting the cached file immediately after storing). This means there are 3 (three) instances of a file on the disk at some point in time, and still 2 instances after Carrierwave is done if you do not remove...
How to define height of a div as percentage of its variable width
This is useful if, for example, you want to use a background-image that has to scale with the width and the div should only have the height of the picture.
html:
<div class="outer">
<div class="inner">
</div>
</div>
css:
.outer {
width: 100%;
background-image: image-url('background.png');
background-size: cover;
}
.inner {
padding-top: 60%;
}
How does it work?
There are several CSS attributes that can handle values as percentage. But they use different other attributes as "reference value...
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, {}, ['']] }
...
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...