Ruby has this handy block shortcut map(&:to_i)
for map { |x| x.to_i }
. However, it is limited to argument-less method invocations.
To call a method with an argument, you usually need to use the full block form. A common and annoying case is retrieving values from a list of hashes (imagine using a JSON API):
users = [ { name: 'Dominik', color: 'blue' }, { name: 'Stefan', color: 'red'} ]
names = users.collect do |user|
user[:name]
end
If you're using Rails 5+, this example is covered by Enumerable#pluck
(`users.pluck(:name)...
Since late 2015, all major browsers (still excluding Firefox) support pointing device media queries. These can be used to distinguish e.g. coarse from fine pointers (e.g. finger vs mouse), or a device with hover support from one without (e.g. desktop with mouse vs tablet).
When hover styles modify the DOM, most mobile devices activate the hover styles on first tap. A second tap is required to trigger a click
. While this can be handy, at times it makes the UX worse.
Another issue with hover styles is that they tend to st...
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")
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...
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...
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.
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
...
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).
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 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 ...
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:
URI.join(root_url, @user.contract.url)
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...
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.
Simple solution in modern JavaScript, e.g. for use in the client's browser:
function svgUri(text) {
let svg = `
<svg width="320" height="240" xmlns="http://www.w3...
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. ;)
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...
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...
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:
CTRL +
and CTRL -
so it covers most of the window area. Leave a little padding on the left and right so...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.
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, ...
The gist is:
span
line-height
for the spacing between lines ("margin")box-shadow
to control the line background size ("padding")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...
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)
One solution...
Slides for Henning's talk on Sep 21st 2017.
print('script start')
html = get('/foo')
print(html)
print('script end')
Script outputs 'script start'
, (long delay), '<html>...</html>'
, 'script end'
.
print('script start')
get('foo', done: function(html) {
print(html)
})
print('script end')
Script outputs 'script start'
, `'...
Hack to implement an inverted "night mode" theme with a few lines of CSS.
Colors in images are preserved.
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...
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 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.
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...
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...
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%;
}
There are several CSS attributes that can handle values as percentage. But they use different other attributes as "reference value...
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...