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...
ActiveRuby
Looks like ActiveState is trying to market a new Ruby distribution for Enterprises:
ActiveRuby Enterprise Edition is designed for businesses with large Ruby deployments in essential, mission-critical applications that, when down, could cost your business in lost revenue and a damaged reputation. Deploy Ruby with confidence knowing you're using the most secure, enterprise-grade builds for the platforms that power your business. You'll get priority access to our Ruby experts for technical support and best prac...
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?...
Ruby: Return boolean for regex comparison
A collection of code snippets which return a boolean value for a regex comparison.
regexp.match?(string) # Recommended for Ruby >= 2.4
!!(string =~ regexp) # Recommended for older Rubies
regexp === string
!(regexp !~ string)
The Ruby 2.4 method Regexp#match?
does not set globals like $~
or $1
, so it should be more performant.
Choosing the right gems for your project
Adding a gem means you take over the liability towards the external code.
Checklist
Based on "To gem, or not to gem":
- Gem is really needed (prefer writing your own code for simple requirements without many edge cases)
- Gem is tested well (coverage and quality)
- Gem has a good code quality
- Gem's licence fits to the project requirement
- Try to avoid gems that do much more than your requireme...
rbenv: A basic introduction
Why
We have projects that have been developed using many different versions of Ruby. Since we do not want to constantly update every old project, we need to have many Ruby versions installed on our development machines.
Rbenv does that for us.
How it works
Rbenv installs ruby version and ruby gems to ~/.rbenv/versions/VERSION_NUMBER/...
. This way many different Rubies can be installed at once.
When you run ruby
or gem
or bundler
or any other Ruby binary
- rbenv looks for a file...
When upgrading/downgrading RubyGems and Bundler on a server, you must clear bundled gems
On application servers, gems are usually bundled into the project directory, at a location shared across deployments.
This is usually shared/bundle
inside your project's root directory, e.g. /var/www/your-project/shared/bundle/
.
If you can't find that, take a look at current/.bundle/config
and look for BUNDLE_PATH
.
When you are changing the version of RubyGems or Bundler on a system where gems are installed this way, you must wipe that bundle directory in addition to the user and system gems or gems that are already ins...
Ruby 1.8.7: Bundler crashes with "deadlock" and core dump
Error
deadlock 0x7f8a4160a360: sleep:- (main) - /home/me/.rbenv/versions/1.8.7-p375/lib/ruby/gems/1.8/gems/bundler-1.14.3/lib/bundler/worker.rb:43
deadlock 0x7f8a38c03b08: sleep:- - /home/me/.rbenv/versions/1.8.7-p375/lib/ruby/gems/1.8/gems/bundler-1.14.3/lib/bundler/worker.rb:56
*** longjmp causes uninitialized stack frame ***: /home/me/.rbenv/versions/1.8.7-p375/bin/ruby terminated
... followed by a backtrace, memory map and more.
Fix
The culprit seems to be Bundler 1.14 when used with Ruby 1.8.7. [Downgrade to the maximu...
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
How to install guard-livereload 2.5.2 on Ruby < 2.2.5
There are some inconvenient Gem dependencies. Resolve them by adding/modifying these lines in your Gemfile:
gem 'guard-livereload', '>= 2.5.2', require: false # Fixes a security issue
gem 'listen', '< 3.1' # 3.1 requires Ruby 2.2.5
It is not possible to install guard-livereload
2.5.2 on Ruby 1.8.7 because it depends on guard
2.8, which requires Ruby 1.9.
JSONP for Rails
The rack-contrib gem brings a JSONP middleware that just works™. Whenever a JSON request has a callback
parameter, it will wrap the application's JSON response appropriately.
The project is a bit dated, but the JSONP middleware is ok.
[jruby] TruffleRuby Status, start of 2017
TruffleRuby is an experimental Ruby implementation that tries to achieve ~10x performance over MRI.
This has been on our radar for a while. They seem to have made significant progress running Rails, reducing start-up time and becoming runtime-independent of the JVM.
Also see [Running Optcarrot, a Ruby NES emulator, at 150 fps with the GUI!](https://eregon.me/blog/2016/11/28/optcarrot.htm...
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:
...
Fix Rubygems binary error: undefined method `activate_bin_path' for Gem:Module (NoMethodError)
So you're getting an error like this:
undefined method `activate_bin_path' for Gem:Module (NoMethodError)
Here is what happened:
- You installed a recent version of Rubygems
- You installed some gems that install a binary (like
bundle
,rake
orrails
) with code that only works with modern Rubygems versions - You downgraded Rubygems to an older versions, which doesn't change any binaries
- When calling binaries with the old Rubygems version, it cannot process the line
Gem.activate_pin_path(...)
that was written out by th...
Net::SSH::Exception: could not settle on encryption_client algorithm
TL;DR: Update the 'net-ssh' gem by adding to your Gemfile
:
gem 'net-ssh', '=2.9.1'
Now run bundle update net-ssh
. It has no dependencies so it shouldn't update other gems.
If you're using Ruby 1.8.7 and want to update net-ssh to a version > 2.9.1
you also need to add this to your gemfile:
gem 'backports', :require => false
... and in your deploy.rb
add this:
require 'backports/1.9.2/array/select'
Background
You propably have an older version of Capistrano and thereby an older version of `n...
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...
A collection of graph and diagram tools
- Plot graphs in Ruby
- WebGraphviz renders in your browser via JavaScript (to store the rendered graph, extract the SVG using your browser's DOM inspector)
- GraphViz with DOT: Online http://graphs.grevian.org/graph https://graphviz.christine.website/ or offline https://makandracards.com/makandra/1589-auto-generate-state_machine-graphs-as-png-images
- Balsamiq
- Draw.io
- [Excalidraw](https:...
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_heredoc
vs.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...
Linux: Using grep with a regular expression
You can use three different versions of the regular expression syntax in grep
:
- basic:
-G
- extended:
-E
(POSIX) - perl:
-P
(PCRE)
Difference between basic and extended:
In basic regular expressions the meta-characters '?', '+', '{', '|', '(', and ')' loose their special meaning; instead use the backslashed versions '?', '+', '{', '|', '(', and ')'.
Difference between extended (POSIX) and perl (PCRE): E.g. \d
is not supported in POSIX.
This g...
Debugging cucumber feature with javascript + firefox vnc
TL;DR Debugging problems with javascript errors in cucumber tests is sometimes easier in the browser. Run the test, stop at the problematic point (with Then pause
from Spreewald 1.7+) and open VNC for Firefox.
Features:
- It does not freeze your server like when you're using a debugger. (Compared to the
Then console
step) - It enables interacting with the server. (Compared to taking screenshots in Capybara)
- It is a faster alternat...
Howto: Free disk space when /boot is full
Easy mode
This method will remove automatically installed packages that no other packages depend on any more. This, of course, includes obsolete kernel versions, with the explicit exception of the currently running kernel, the kernel version that was installed on the system before that and, of course, the latest updated version of the kernel. However, it will also remove any and all other packages that have been marked as installed automatically but have no other packages depending on them. This could lead to unexpected removal of packag...