Generating barcodes with the Barby gem
Barby is a great Ruby gem to generate barcodes of all different sorts.
It includes support for QR codes via rQRCode; if you need to render only QR codes, you may want to use that directly.
Example usage
Generating a barcode is simple:
>> Barby::Code128.new('Hello Universe').to_png
=> "\x89PNG\r\n\u001A..."
Configuration
Barby supports several barcode types and you must require all necessary files explicitly.
For the example a...
Rails: Default generators
This is a visualization of the files that will be generated by some useful rails generators. Invoke a generator from command line via rails generate GENERATOR [args] [options]. List all generators (including rails generators) with rails g -h.
| generator | model | migration | controller | entry in routes.rb
|
views | tests |
|---|---|---|---|---|---|---|
| scaffold | ✔ | ✔ | ✔ | ✔ | ✔ | ✔ |
| resource | ✔ | ✔ | ✔ ... |
SASS: Defining linear sizes
Just dumping this in case somebody might need it.
When you need a CSS value (a padding, margin, height etc) to shrink/grow proportionally with the parent element, you normally use percentage values. However, if you need specific values at two given widths, you need to turn to linear functions. The mixin below gives you just that.
// Call with two desired values at two different widths.
// Returns a calc() expression that will scale proportionally between those two.
// Example:
// Spaci...
How to show an ordered crontab
Crontabs are often unordered, especially when generated for an application where you usually group tasks by their domain/scope.
An example crontab might look like this:
# Begin Whenever generated tasks for: project100
MAILTO="log@example.com"
MAILFROM="cron@example.com"
# When server is booting up, ensure Sidekiq is running
@reboot start_sidekiq
23 8 * * * baz
30 * * * * plop
5 8 * * * bar
1 0 * * * foo
# End Whenever generated tasks for: project100
While you can human-parse this one easily, crontabs with several lines are hard ...
Haml: Prevent whitespace from being stripped in production
Disclaimer
This is not an issue in newer versions of HAML (starting with 5.0.0), as the ugly-option was removed so that in development everything is rendered ugly, too.
Problem
When HTML is rendered from HAML in production or staging environment, whitespace is removed to reduce the download size of the resulting pages. Therefore it might happen that whitespace you see in development is missing in production or staging.
Here is an example of two inlined bootstrap buttons in a t...
Running external commands with Open3
There are various ways to run external commands from within Ruby, but the most powerful ones are Open3.capture3 and Open3.popen3. Since those can do almost everything you would possibly need in a clean way, I prefer to simply always use them.
Behind the scenes, Open3 actually just uses Ruby's spawn command, but gives you a much better API.
Open3.capture3
Basic usage is
require 'open3'
stdout_str, error_str, status = Open3.capture3('/some/binary', 'with', 'some', 'args')
if status.success?...
RestClient / Net::HTTP: How to communicate with self-signed or misconfigured HTTPS endpoints
Occasionally, you have to talk to APIs via HTTPS that use a custom certificate or a misconfigured certificate chain (like missing an intermediate certificate).
Using RestClient will then raise RestClient::SSLCertificateNotVerified errors, or when using plain Net::HTTP:
OpenSSL::SSL::SSLError: SSL_connect returned=1 errno=0 state=SSLv3 read server certificate B: certificate verify failed
Here is how to fix that in your application.
Important: Do not disable certificate checks for production. The interwebs are full of people say...
VCR: Inspecting a request
Using VCR to record communication with remote APIs is a great way to stub requests in tests. However, you may still want to look at the request data like the payload your application sent.
Using WebMock, this is simple: Make your request (which will record/play a VCR cassette), then ask WebMock about it:
expect(WebMock).to have_requested(:post, 'http://example.com').with(body: 'yolo')
Easy peasy.
Related cards
Open dialogs from shell scripts
Using the dialog command you can launch ASCII-art dialogs from your shell scripts.
Check out man dialog for a list of supported dialog types. Aside from simple text boxes or choice dialogs, it supports more advanced interactions like file pickers or progress bars.
Example: Yes/no choice
dialog --yesno "Erase the world?" 0 0
Example: Menu with multiple opt...
CSS tests and experiments
The pages listed here contain tests and experiments about features, possibilities, browsers’ bugs concerning CSS.
That is, over 200 experiments.
CSS font metrics in detail
Line-height and vertical-align are simple CSS properties. So simple that most of us are convinced to fully understand how they work and how to use them. But it’s not. They really are complex, maybe the hardest ones, as they have a major role in the creation of one of the less-known feature of CSS: inline formatting context.
For example, line-height can be set as a length or a unitless value 1, but the default is normal. OK, but what normal is? We often read that it is (or should be) 1, or maybe 1.2, even the CSS spec is unclear on that...
Capybara: Disable sound during Selenium tests
If the application under test makes sound, you probably want to disable this during integration testing.
You can use the args option to pass parameters to the browser. For Chrome:
Capybara.register_driver :selenium do |app|
Capybara::Selenium::Driver.new(app, browser: :chrome, args: ["--mute-audio"])
end
I haven't found a corresponding command line option for Firefox.
Hat tip to kratob.
How to search through logs on staging or production environments
We generally use multiple application servers (at least two) and you have to search on all of them if you don't know which one handled the request you are looking for.
Rails application logs usually live in /var/www/<project-environment-name>/shared/log.
Web server logs usually live in /var/www/<project-environment-name>/log.
Searching through single logs with grep / zgrep
You can use grep in this directory to only search the latest logs or zgrep to also search older (already zipped) logs. zgrep is used just like grep ...
Never use SET GLOBAL sql_slave_skip_counter with a value higher than 1
If you have a replication error with MySQL and you know the "error" is okay (e.g. you've executed the same statement at the same time on 2 masters which sync each other), you can skip this error and continue with the replication without having to set up the slave from the ground up.
stop slave;
set global sql_slave_skip_counter = 1;
start slave;
But what if you have multiple errors which you want to skip? (e.g. you've executed multiple statement at the same time on 2 masters which sync each other)
Still do not use a value highe...
Error "undefined method last_comment"
This error message may occur when rspec gets loaded by rake, e.g. when you migrate the test database.
NoMethodError: undefined method 'last_comment' for #<Rake::Application:0x0055a617d37ad0>
Rake 11 removes a method that rspec-core < 3.4.4 depends on. To fix, lock Rake to < 11 in your Gemfile:
gem 'rake', '< 11', # Removes a method that rspec-core < 3.4 depends on
Geordi hints
Reminder of what you can do with Geordi.
Note: If you alias Geordi to something short like g, running commands gets much faster!
Note: You only need to type the first letters of a command to run it, e.g. geordi dep will run the deploy command.
geordi deploy
Guided deployment, including push, merge, switch branches. Does nothing without confirmation.
geordi capistrano
Run something for all Capistrano environments, e.g. geordi cap deploy
geordi setup -t -d staging
When you just clon...
How to tackle complex refactorings in big projects
Sometimes huge refactorings or refactoring of core concepts of your application are necessary for being able to meet new requirements or to keep your application maintainable on the long run. Here are some thoughts about how to approach such challenges.
Break it down
Try to break your refactoring down in different parts. Try to make tests green for each part of your refactoring as soon as possible and only move to the next big part if your tests are fixed. It's not a good idea to work for weeks or months and wait for all puzzle pieces ...
Enabling ** in your bash
You may know the double asterisk operator from Ruby snippets like Dir['spec/**/*_spec.rb'] where it expands to an arbitrary number of directories.
However, it is disabled by default on most systems. Here is how to enable it.
If you check your globstar shell option, it is probably disabled:
$ shopt globstar
globstar off
In that case, ** behaves just like * and will match exactly 1 directory level.
$ ls spec/**/*_spec.rb
spec/models/user_spec.rb
To enable it, run
shopt -s globstar
The double ast...
Ruby: String representations of regular expressions
Ruby's regular expressions can be represented differently.
When serializing them, you probably want to use inspect instead of to_s.
For the examples below, consider the following Regexp object.
regexp = /^f(o+)!/mi
to_s
Using to_s will use a format that is correct but often hard to read.
>> regexp.to_s
=> "(?mi-x:^f(o+)!)"
inspect
As the Ruby docs say:
...
It's OK to put block elements inside an <a> tag
In general, you should not put a block element inside an inline element. So don't do this:
<span>
<div>text</div>
</span>
The browser will think you wrote invalid HTML by accident, and will sometimes reorder elements silently.
There is one notable exception: It's OK to wrap block elements in a <a> tag in HTML5 (not 4). The spec says:
The a element may be wrapped around entire paragraphs, lists, tables, and so forth, even entire sections, so long ...
Puppet: Could not evaluate: Field 'device' is required
If you get an error like this for a puppet mount:
$ > puppet agent --test
Info: Retrieving pluginfacts
Info: Retrieving plugin
Info: Loading facts
Info: Caching catalog for example.makandra.de
Info: Applying configuration version '1483001792'
Info: Computing checksum on file /etc/fstab
Info: FileBucket got a duplicate file {md5}34b9adc036cf1dbd2392df84f921547d
Notice: /Stage[main]/Foobar/Swap_file::Files[default]/Mount[/var/swapfile]/ensure: defined 'ensure' as 'defined'
Error: /Stage[main]/Foobar/Swap_file::Files[default]/Mount[/var/s...
Bundler: Gemfile.lock is corrupt & gems are missing from the DEPENDENCIES section
So you're getting this failure when running bundle install on an older project:
Your Gemfile.lock is corrupt. The following gems are missing from the DEPENDENCIES section: 'archive-tar-minitar' 'hoe' 'rcov'
This happens when you are using a new version of Bundler with a project that was bundled with a very old version of Bundler. For reasons unknown, the Bundler dependency API returns different dependencies for some gems (like ruby-debug or rainpress) than the dependencies found in the downloaded gemspecs. While old versi...
Summarizing heredoc in Ruby and Rails
This card tries to summarize by example the different uses of heredoc.
- In Ruby
<<vs.<<-vs.<<~ - In Rails
strip_heredocvs.squish
strip_heredoc should be used for a text, where you want to preserve newlines. (multi-line -> multi-line)
squish should be used for a text, where you want to squish newlines. (multi-line -> one-line)
Ruby 2.3+
def foo
bar = <<~TEXT
line1
line2
line3
TEXT
puts bar.inspect
end
foo => "line1\nline2\nline3\n"
Read more: [Unindent HEREDOCs in Ruby 2.3](/m...
A case for different breakpoints
The linked article states that CSS breakpoints should group "similar" screen sizes and thus be at:
- 600px "narrow"
- 900px "medium"
- 1200px "wide"
- (1800px) "huge"
By choosing these breakpoints, most device screens will be somewhere between two breakpoints, and not at the very edge of them.
The ranges could be called:
- narrow (< narrow)
- medium (narrow - medium)
- normal (medium - wide)
- wide (wide - huge)
- huge (> huge)