How to access before/after pseudo element styles with JavaScript
Accessing pseudo elements via JavaScript or jQuery is often painful/impossible. However, accessing their styles is fairly simple.
Using getComputedStyle
First, find the element in question.
let element = document.querySelector('.my-element') // or $('.my-element').get(0) when using jQuery
Next, use JavaScript's getComputedStyle
. It takes an optional 2nd argument to filter for pseudo elements.
let style = window.getComputedStyle(element, '::before')
let color = style.getPropertyValue('background-color...
Ruby's percent notation can do more than strings
Percent Notation
We already know that that we can create strings using the percent notation:
%(<foo="bar's ton">)
is perfectly fine Ruby.
Modifier
But there is more. The curly brackets ({}
) are interchangable with most unicode characters (e.g. square brackets[]
).
Furthermore, you can add a "modifier" to the percent notation to control the return type of th...
RubyMine: How to add a german spell checker
Grazie Lite
Rubymine 2024.3 bundles Grazie Lite by default. You need to enabled "German" under Settings/Preferences | Editor | Natural Languages
.
Hunspell (legacy)
- Install the
Hunspell
plugin and restart Ruby Mine - Run
sudo apt install hunspell-de-de
- Select
/usr/share/hunspell/de_DE.dic
in File > Settings > Editor > Spelling > Custom Directory +

# ...
end
To accomplish something similar in ruby 1.8, use:
def match(value, options = {})
ignore = options.fetch(:ignore)
# ...
end
How to examine an unknown Ruby object
When debugging your application, you will come across objects created by some gem or framework. You don't have the source code at hand, still need to inspect this object. Here are some tools to do so:
Relevant methods
@object.methods - Object.instance_methods
returns a list of methods excluding methods inherited from Object
. This makes the methods list drastically more relevant. You can also try subtracting other base classes like ActiveRecord::Base.methods
etc.
To further narrow it down you can also just look at public methods...
Rbenv: How to remove a gem installed from a Github source
Normally you can list all gems of the current ruby version with gem list
, which also includes the gems of you Gemfile
. These can be uninstalled with gem uninstall gemname
.
List and uninstall a gem installed via Bundler from Github
This does not work for gems installed directly from Github. They do not appear in gem list
.
Show all gems installed via Github by bundler:
ls ~/.rbenv/versions/2.4.1/lib/ruby/gems/2.4.0/bundler/
Remove a gem installed via Github by Bundler:
rm -rf ~/.rbenv/versions/2.4.1/lib/ruby/gems/2....
How to let passenger restart after deployment with capistrano
Phusion Passenger changed the way how it gets restarted several times. Through the project's history, these all were valid:
touch tmp/restart.txt
sudo passenger-config restart-app /path/to/app
passenger-config restart-app /path/to/app
You should not need to know which one to use. Instead, the capistrano-passenger gem will choose the appropriate restart mechanism automatically based on your installed the passenger version.
Installation
-
Add to your
Gemfile
:gem 'capistr...
An incomplete guide to migrate a Rails application from paperclip to carrierwave
In this example we assume that not only the storage gem changes but also the file structure on disc.
A general approach
Part A: Create a commit which includes a script that allows you to copy the existing file to the new file structure.
Part B: Create a commit which removes all paperclip logic and replace it with the same code you used in the first commit
Part A
Here are some implementation details you might want to reuse:
- Use the existing models to read the files from
- Use your own carrierwave models to write t...
Raising JavaScript errors in Ruby E2E tests (RSpec, Cucumber)
A JavaScript error in an E2E test with Selenium will not cause your test to fail. This may cause you to miss errors in your frontend code.
Using the BrowserConsole
helper below you can check your browser's error console from your E2E tests.
The following will raise BrowserConsole::ErrorsPresent
if there is an error on the browser console:
BrowserConsole.assert_no_errors!
Ignoring errors
You can ignore errors by their exact message:
BrowserConsole.ignore('Browser is burning')
You can ignore errors with me...
Rails < 5: How to get after_commit callbacks fired in tests
If you use transactional_fixtures
or the database_cleaner gem with strategy :transaction
, after_commit
callbacks will not be fired in your tests.
Rails 5+
Rails 5 has a fix for this issue and no further action is needed.
Rails 3, Rails 4
Add the gem test_after_commit to your test
group in the Gemfile and you are done. You don't need to change the database strategy to deletion
(wh...
Ruby: How to use prepend for cleaner monkey patches
Let's say you have a gem which has the following module:
module SuperClient
def self.foo
'Foo'
end
def bar
'Bar'
end
end
For reasons you need to override foo
and bar
.
Keep in mind: Your code quality is getting worse with with each prepend
(other developers are not happy to find many library extensions). Try to avoid it if possible.
- Add a
lib/ext/super_client.rb
to your project (see How to organize monkey patches in Ruby on Rails projects) - Add the extension, which ov...
How to write a good changelog
We want to keep a changelog for all gems we maintain. There are some good practices for writing a changelog that adds value, please stick to these.
- Add a notice to the README's contribute section about the changelog
- For every release update the changelog
- Note the date format yyyy-mm-tt
What is a changelog?
A changelog is a file which contains a curated, chronologically ordered list of notable changes for each version of a project.
Why keep a changelog?
To make it easier for users and...
How to make changes to a Ruby gem (as a Rails developer)
At makandra, we've built a few gems over the years. Some of these are quite popular: spreewald (> 1M downloads), active_type (> 1M downloads), and geordi (> 200k downloads)
Developing a Ruby gem is different from developing Rails applications, with the biggest difference: there is no Rails. This means:
- no defined structure (neither for code nor directories)
- no autoloading of classes, i.e. you need to
require
all files yourself - no
active_support
niceties
Also, their scope...
Haml: Generating a unique selector for an element
Having a unique selector for an element is useful to later select it from JavaScript or to update a fragment with an Unpoly.
Haml lets you use square brackets ([]
) to generate a unique class name and ID from a given Ruby object. Haml will infer a class
attribute from the given object's Ruby class. It will also infer an id
attribute from the given object's Ruby class and #id
method.
This is especially useful with ActiveRecord instances, which have a persisted #id
and will hence **generate the same selector o...
Rails: Flagging all cookies as secure-only to pass a security audit
Why secure-only cookies used to be necessary
Cookies have an optional secure
flag. It tells the browser to not send the cookie for a non-https request.
It used to be important to activate the secure
flag even on sites that automatically redirect users from http://
to https://
. The reason was that most users will only enter a scheme-less domain like makandra.de
into their location bar, which will default to `http://m...
How to fill in multiple lines in a textarea with cucumber
If you want to fill in textareas with multiple lines of text (containing line breaks / new lines) you can use Cucumber's docstrings:
And I fill in "Comment" with:
"""
This is a long comment.
With multiple lines.
And paragraphs.
"""
The step definition is part of the spreewald gem
Fix for Ruby 1.8.7 installation error
On some machines, installing Ruby 1.8.7 with ruby-build can lead to this error:
math.c:37:13: error: missing binary operator before token "("
Try instead to install ruby-1.8.7-p374
.
Using the Ruby block shortcut with arguments
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)...
Whenever: Don't forget leading zeros for hours!
Whenever is a Ruby gem that provides a nicer syntax for writing and deploying cron jobs.
Leading zeros are important for whenever if you use the 24-hours format!
This schedule.rb
:
every 1.day, at: '3:00', roles: [:primary_cron] do
runner 'Scheduler.delay.do_things'
end
will lead to this crontab entry (crontab -l
) with the default configuration:
0 15 * * * /bin/bash -l -c 'cd /var/www/my-project/releases/20180607182518 && bin/rails runner -e production '\''Scheduler.delay.do_things'\'''
Which would run on 3...
Ruby: All Errno::ERROR constants inherit from SystemCallError
To catch all possible exceptions from a network call, we need to rescue
many error classes like this:
rescue SocketError, Errno::ECONNREFUSED, Errno::ECONNRESET, Errno::ECONNABORTED, Errno::EHOSTUNREACH, OpenSSL::SSL::SSLError, MyHttpLib::BadResponse
You can shorten this a bit by rescuing SystemCallError
, which is a base class for all Errno::
exceptions:
rescue SocketError, SystemCallError, OpenSSL::SSL::SSLError, MyHttpLib::BadResponse
Some high-level ...
ActiveRecord::Store: migrate data in store
When you need to store structured data (like Ruby hashes) in a single database column with ActiveRecord, a simple way is to use PostgreSQL's jsonb
columns. ActiveRecord will automatically serialize and deserialize your Hash to and from JSON, and you can index JSON paths for fast reads.
As an alternative, ActiveRecord::Store
offers a way to store hashes in a single database column. This card will show you how to migrate those hashes in an ActiveRecord::Migration
by example:
...
Capistrano + Rails: Tagging production deploys
Just like Ruby Gems tag their version releases to the corresponding Git commit, it can be helpful to track production deploys within the commit history. This task does the tagging for you.
Capistrano 3
# lib/capistrano/tasks/deploy.rb
namespace :deploy do
...
desc 'Tag the deployed revision'
task :tag_revision do
date = Date.today.to_s
puts `git tag deploy-#{date} #{fetch :current_revision}`
puts `git push --tags origin`
end
end
# config/deploy/production.rb
after 'deploy:finished', 'deploy:tag_revi...
Bundler error: Downloading gem revealed dependencies not in the API
Recent Bundler (1.16.1) started complaining about missing dependencies in the Gemfile. This is due to a stricter handling of specifications (see attached link).
The error message looks like this:
Downloading example-gem-1.2.3 revealed dependencies not in the API or the lockfile (other-gem (< 3)).
Either installing with `--full-index` or running `bundle update example-gem` should fix the problem.
However, bundle install --full-index
did not any better for me, and bundle update
is not always a viable solution.
Easiest solut...
Fixing: Gem::Package::PathError: installing into parent path is not allowed
This might be a known issue with Rubygems 2.5.1. This will help:
gem update --system