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...

Getting error Bundler::Plugin::API::Source

Error:

/home/.../ruby/gems/2.1.0/gems/bundler-1.14.3/lib/bundler/rubygems_ext.rb:45:in `full_gem_path': uninitialized constant Bundler::Plugin::API::Source (NameError)

Solution: Upgrade Rubygems beyond 2.6.9.

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...

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 ...

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.

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 or rails) 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...

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:

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...

How to fix: Bundler 1.13 breaks parallel_tests

When running tests via parallel_tests, you may encounter an error:

cannot load such file -- parallel_tests/gherkin/runtime_logger
Error creating formatter: ParallelTests::Gherkin::RuntimeLogger (LoadError)

This will happen when you upgrade Bundler to version 1.13.x and appears to be "by design" since there is a Bundler config option to restore previous behavior.

You can fix it by setting that flag. You should commit the resulting config file into the repository!

bundle config --local disable_exec_load true

There is a Git...

Aruba: Stubbing binaries

When testing your command line application with Aruba, you might need to stub out other binaries you don't want to be invoked by your test.

Aruba Doubles is a library that was built for this purpose. It is not actively maintained, but works with the little fix below.

Installation

Install the gem as instructed by its README, then put this Before block somewhere into features/support:

Before do
  Arub...

Hide a Rake task from the `rake -T` list

A Rake task appears in rake -T if it has a description:

desc 'Compile assets'
task :compile do
  ...
end

To not list it, simply omit the description:

task :compile do
  ...
end

You can also hide a Rake task that has been defined by someone else (like a gem) by removing the description:

Rake::Task['compile'].clear_comments

Or you can whitelist which tasks should be listed:

visible_tasks = %w(compile build package)
Rake::Task.tasks.each do |task|
  visible_tasks.include?(task.name) or task.clear_comments
en...

Subclassing module

Yesterday I stumbled across a talk in which the guy mentioned module sub-classing. I was curious what you can do with it and found his blog post with a cool example. It allows you to inject some state into the module you are including elsewhere. Check it out!

class AttributeAccessor < Module
  def initialize(name)
    @name = name
  end

  def included(model)
    super
    define_accessors
  end

  private

  def define_accessors
    ivar = "@#{@name}"
    define_writer(ivar)
    define_reader(ivar)
  end

  def define_writer(ivar)
    ...

How to monitor Sidekiq: A working example

In order to have monitoring for Sidekiq (like queue sizes, last run of Sidekiq) your application should have a monitoring route which returns a json looking like this:

{
  "sidekiq": {
    "totals": {
      "failed": 343938,
      "processed": 117649167
    },
    "recent_history": {
      "failed": {
        "2016-11-06": 1,
        "2016-11-07": 46,
        "2016-11-08": 0,
        "2016-11-09": 0,
        "2016-11-10": 0
      },
      "processed": {
        "2016-11-06": 230653,
        "2016-11-07": 230701,
        "2016-11-08"...

mceachen/closure_tree: Easily and efficiently make your ActiveRecord models support hierarchies

Closure_tree lets your ActiveRecord models act as nodes in a tree data structure.

This promises a few improvements over the battle-tested ancestry gem, such as:

  • Better performance
  • Pre-ordered trees (painful to do with ancestry)
  • Holds a mutex during tree manipulations (an issue with ancestry, where concurrent updates can cause deadlocks and corrupt data).

It has some more moving parts than ancestry though (see below).

Implementation
--------------...

Detecting if a Ruby gem is loaded

Detect if a gem has been activated

A gem is activated if it is either in the current bundle (Gemfile.lock), or if you have manually activated it using Kernel#gem (old-school).

To detect if e.g. activerecord has been activated:

if Gem.loaded_specs.has_key?('activerecord')
  # ActiveRecord was activated
end

Detect if a particular gem version has been activated

To detect if e.g. activerecord ma...

makandra/gemika: Helpers for testing Ruby gems

We have released a new library Gemika to help test a gem against multiple versions of Ruby, gem dependencies and database types.

Here's what Gemika can give your test's development setup (all features are opt-in):

  • Test one codebase against multiple sets of gem dependency sets (e.g. Rails 4.2, Rails 5.0).
  • Test one codebase against multiple Ruby versions (e.g. Ruby 2.1.8, Ruby 2.3.1).
  • Test one codebase against multiple database types (currently MySQL or PostgreSQL).
  • Compute a matrix of all possib...