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...
RSpec expects pending tests to fail
When flagging a spec that will be implemented later as pending
, include a failing spec body or RSpec 3 will consider the pending test as failing.
The reasoning is: If the spec is flagged as pending but passes, it should not be pending. So these will fail:
it 'does something' do
pending
end
it 'does something else' do
pending
expect(1).to eq(1)
end
The first case may be unexpected, if you just wanted to write down that something should eventually happen that will be implemented later.
Instead, ...
Heads up! Years are always floats in Rails < 4
Watch out when saying something like 1.year
in Rails. The result is not a Fixnum
and can cause unexpected errors when the receiving end expects a Fixnum
.
While anything from seconds to months are Fixnum
s, a year is a Float
in Rails -- when called on a Fixnum
itself:
>> 10.seconds.class
=> Fixnum
>> 2.minutes.class
=> Fixnum
>> 24.hours.class
=> Fixnum
>> 28.days.class
=> Fixnum
>> 9.months.class
=> Fixnum
>> 1.year.class
=> Float # Boom.
While they are [technically correct](http:...
Centering with CSS vertically and horizontally (all options overview)
There are a million ways to center <div>
s or text in CSS, horizontally or vertically. All the ways are unsatisfying in their own unique way, or have restrictions regarding browser support, element sizes, etc.
Here are two great resources for finding the best way of aligning something given your use case and browser support requirements:
How to center in CSS
: A long form that lets you define your use case and browser support requirements, then shows you the preferred way of aligning.
[Centering CSS: A com...
Think twice before using application names in your variables and methods
I recently had fun with replacing a custom video plattform ("mycustomtv") in one of our applications. I learned a lot about naming stuff.
youtube_mycustomtv_chooser
is a bad name for a directive.
Why?
- if you add, for example, other video systems like vimeo, the name of the method either lies or will get longer.
- if you replace one system, you will have to change the method and all of its occurrences (and you're very lucky if it is only one poorly named thing in your application)
What would be a better solution?
Abstract fro...
Katapult 0.4.0 released
Features
- Generating a project README
- Finally: Support for modelling associations between models in your application model! Example:
# lib/katapult/application_model.rb
model 'Cart' do |cart|
cart.belongs_to 'User'
end
crud 'User' do |user|
user.attr :fullname
end
Cucumber: How to avoid VCR errors for unused requests in pending tests
When you have a pending Cucumber step (or feature) that also uses an existing VCR cassette, your pending test may fail at the very end with an error like this:
There are unused HTTP interactions left in the cassette:
- [get ...] => [200 ...]
- [get ...] => [200 ...] (VCR::Errors::UnusedHTTPInteractionError)
The error happens because your VCR is configured to complain about cassettes that contain extra requests which your test did not use. This is often a good configuration.
If you do not want to change your whole test suite...
Katapult 0.3.0 released
Katapult 0.3.0 brings Rails 5 and Ruby 2.5 support with a new design, plus a ton of smaller features, fixes and improvements.
Features
- Generating a Rails 5.1.4 app on Ruby 2.5.0
- Dropped asset pipeline in favor of Webpacker
- The generated application now has a sleek, simple design based on Bootstrap
- Employing Unpoly
- New application model DSL shortcut
crud
for "create a model and a web UI with crud actions" - The generated application model is now a transformable e...
Ruby: Using all? with empty collection
Enumerable#all? returns true
for an empty collection. This totally makes sense but you have to think about it when making assumptions on relations which might be empty.
[].all?(&:will_never_be_called_here) => true
Example with empty collection
class Researcher < ActiveRecord::Base
has_many :papers
end
class Paper
validates :topic, inclusion: { in: ['computer_science', 'mathematics', 'economy'] }
end
Easy goal: Delete all researches who write onl...
How to mirror a git repo to a new remote
Say you want to move a git repository from one remote (perhaps Github) to another (perhaps Gitlab).
If you have the repo checked out, you still should make sure to mirror all branches of the old remote, not only those you happen to have checked our. Otherwise the target repo will become a copy of your current repo, and not the source repo, potentially missing commits. You can use this:
git remote rename origin old-origin
git remote add origin <new-remote>
git fetch old-origin --prune
git push --prune origin +refs/remotes/old-origin/*:r...
How to: Run webpack dev server with vcap.me
If your Rails application is using Webpack you need to serve assets on the same host as you application runs, otherwise you will see the following errors in your browser console:
[WDS] Disconnected!
Invalid Host header
So if you are using awesome.vcap.me:3000
you need to start the webpack-dev-server
with a different host than localhost (0.0.0.0
):
bin/webpack-dev-server --host awesome.vcap.me
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.
How to debug Rails autoloading
ActiveSupport::Dependencies takes care of auto-loading any classes in development. This is usually useful, but when you run into issues with the Rails autoloader, you should take a look at what it's doing.
For me this was useful in an "exciting" case of auto-loading classes inside a thread which caused the application to stop responding.
Rails 4.x
ActiveSupport::Dependencies includes logging support. It is easy to use:
ActiveSupport::Dependencies.logger = Rails.logger
Rails 5+
[Logging support was removed](https://github...
PostgreSQL: How to UPDATE multiple attributes with multiple joins
This is an extension to PostgreSQL vs MySQL: How to UPDATE using a JOIN.
UPDATE employees
SET department_name = departments.name,
department_area = areas.name
FROM departments, areas
WHERE employees.department_id = departments.id
AND departments.id = areas.department_id
About-Payments: Platform to compare payment providers
About-Payments is here to help you to accept payments online and
find the best payment service provider for your e-commerce business.
Sprites with Compass
Using CSS sprites for background images is a technique for optimizing page load time by combining smaller images into a larger image sprite.
There are ongoing arguments on how useful this still is, as modern browsers become more comfortable to load images in parallel. However, many major websites still use them, for example amazon, [facebook](...
How to query PostgreSQL's json fields from Rails
PostgreSQL offers a really handy field type: json
. You can store any JSON there, in any structure.
While its flexibility is great, there is no syntactic sugar in Rails yet. Thus, you need to manually query the database.
Demo
# Given a Task model with 'details' json column
Task.where("details->>'key' = ?", "value") # matches where 'details' contains "key":"value"
Task.where("details->>'{a,b}' = ?", "value") # matches where 'details' contains "a":{"b":"value"}
Task.where("details->'a'->>'b' = ?", "value") # same as above, but vi...
Font Awesome 5 migration guide
Font Awesome version 5 changed some icon names, and introduces new prefixes fab
, far
, and fas
.
There is a JavaScript shim that you can use as a "quick fix". It allows you to keep v4 icon names on v5.
The linked page includes details on using that, and a migration guide including a list of icon renames.
RSpec: How to check that an ActiveRecord relation contains exactly these elements
To check which elements an ActiveRecord relation contains use the contain_exactly
matcher.
describe User do
let!(:admin) { create(:user, role: 'admin') }
let!(:customer) { create(:user, role: 'customer') }
subject(:users) { User.where(role: 'admin') }
# Recommended (The error output is most helpful)
it { expect(users).to contain_exactly(admin) }
# Other options
it { expect(users).to eq([admin]) }
it { expect(users.pluck(:id).to eq([admin.id]) }
end
In case you have an `ActiveRecord::AssociationRelati...
jQuery: How to attach an event handler only once
With "attaching an event handler once" you possibly mean one of these two things:
Register a function for an event, and discard it once that event has happened
Use one
instead of on
.
$(element).one('eventName', function() { ... });
It has the same API has on
.
When code is run multiple times that registers a function for an event, do that only once
With jQuery, you can de-register callbacks. You can use that to achieve registering a function only once.
function myAction() { ... }; // defined somewhere globally o...
Ruby: control flow with throw and catch
This article will show you how to use throw
and catch
. It's a nice tool to break out of multiple loops when a result is obtained.
Also see our card Ruby: A small summary of what return, break and next means for blocks.
Form letters with LibreOffice Writer
This is painful. Consider using Microsoft Office or switching careers. If you need to write < 20 letters consider doing it manually.
So you didn't listen and here it comes:
- Ignore the Mail Merge Wizard. It will crash or destroy your document.
- Export your addresses, recipient names, etc. as a
.ods
spreadsheet (.xls
,.xlsx
,.ods
). Use any columns that work for you, but be consistent. I like to use one column for the address, one column for the salutation line. - Import the spreadsheet as an address book source: *Tools => Add...
Error during Rails 5 upgrade: Environment data not found in the schema
This error is raised because your old database does not have a configured environment yet, which Rails 5 enforces.
If this error occurs while migrating your parallel test databases, make sure to update the parallel_tests
gem first: current versions fix this. If you're still using Cucumber < v3, the latest version of parallel_tests
will be 2.18.0.
Remember: LoDash syntax is a bit different from UnderscoreJS
Since we are using LoDash instead of UnderscoreJS in recent/current projects, you should keep in mind that their syntax is a bit different.
UnderscoreJS
In UnderscoreJS, methods always return a value:
x = [1, 2, 2]
_.uniq(x) // => [1, 2]
_(x).uniq() // => [1, 2]
If you want to chain multiple calls, you need to start off with a _.chain
, and call value()
to terminate the chain.
_.chain(x).uniq().map(function(i) { return i + 10 }).reverse().value() // => [12, 11]
##...