Fixing the warning Time#succ is obsolete; use time + 1

Chances are you're seeing the warning repeated a lot of times, maybe thousands of times. Here's how to reproduce the issue:

Example 1

# bad code
(Time.current .. Time.current + 1.hour).include?(Time.current)

# Use Range#cover? instead of Range#include? since the former does no typecasting into integers.
(Time.current .. Time.current + 1.hour).cover?(Time.current)

Example 2

# bad code
Post.where(:created_at => min_date.beginning_of_day .. max_date.end_of_day)

# Use 'BETWEEN x AND y'
Post.where(['posts.created_at BETWEEN...

How to emulate simple classes with plain JavaScript

If you want a class-like construct in JavaScript, you can use the module pattern below. The module pattern gives you basic class concepts like a constructor, private state, public methods.

Since the module pattern only uses basic JavaScript, your code will run in any browser. You don't need CoffeeScript or an ES6 transpiler like Babel.

A cosmetic benefit is that the module pattern works without the use of this or prototypes.

Example

Here is an example for a Ruby class that we want to translate into Javascript using the module patter...

Traveling Ruby: self-contained, portable Ruby binaries

Traveling Ruby is a project which supplies self-contained, "portable" Ruby binaries: Ruby binaries that can run on any Linux distribution and any OS X machine. This allows Ruby app developers to bundle these binaries with their Ruby app, so that they can distribute a single package to end users, without needing end users to first install Ruby or gems.

Install or update Chromedriver on Linux

Option 0: Download from the official page (preferred)

Chromedriver must be available in your path. You can add ~/bin to your path like this:

echo "export PATH=$PATH:$HOME/bin" >> $HOME/.bash_profile

If you're also using Geordi, disable automatic updating of chromedriver in ~/.config/geordi/global.yml:

a...

jpmcgrath/shortener

Shortener is a Rails Engine Gem that makes it easy to create and interpret shortened URLs on your own domain from within your Rails application. Once installed Shortener will generate, store URLS and “unshorten” shortened URLs for your applications visitors, all whilst collecting basic usage metrics.

Upgrading a Rails 3.2 application to Ruby 2.1 is really easy

Upgrading from Ruby 1.8.7 to 2.1.2 took me an hour for a medium-sized application. It involved hardly any changes except

  • removing the occasional monkey patch where I had backported functionality from modern Rubies
  • Migrating from require to require_relative where I loaded RSpec factories in Cucumber's env.rb (the Rails application root is no longer in the load path by default)
  • replacing the old debugger with byebug
  • removing sytem_timer from Gemfile (see [this SO thread](http://stackoverflow.com/questions/7850216/how-to-inst...

Using Passenger Standalone for development

For our production servers we use Passenger as a Ruby application server. While it is possible to use Passenger for development as an Apache module, the installation process is not for the faint of heart.

Luckily Passenger also comes as a standalone binary which requires zero configuration.

You can Passenger Standalone as a replacement for Webrick or Thin if you'd like to:

  • Use SSL certificates locally
  • Get performance behavior that is closer to ...

PSA: Dont allow private gems to be pushed to rubygems.org

If you make a gem with Bundler, you will get a rake release task that will instantly publish your gem to rubygems.org for all the world to admire. For private gems this is very bad.

To make sure this cannot happen, rubygems 2.2+ allows you to restrict eligible push hosts:

Gem::Specification.new 'my_gem', '1.0' do |s|
  # ...
  s.metadata['allowed_push_host'] = 'https://gems.my-company.example'
end

In case you already messed up, [follow these instructions to get your gem removed](http://help.rubygems.org/kb/rubygems/removing-an-a...

Speed up JSON generation with oj

Using this gem I could get JSON generation from a large, nested Ruby hash down from 200ms to 2ms.

Its behavior differs from the default JSON.dump or to_json behavior in that it serializes Ruby symbols as ":symbol", and that it doesn't like an ActiveSupport::HasWithIndifferentAccess.

There are also some issues if you are on Rails < 4.1 and want it to replace #to_json (but you can always just call Oj.dump explicitely).

Security warning: Oj does not escape HTML entities in JSON
---------...

Downgrade Bundler in RVM

Confusingly, RVM installs the bundler gem into the @global gemset, which is available to all gemsets and Rubies.

You can get around this and install a particular bundler version like this:

rvm @global do gem uninstall bundler
rvm @global do gem install bundler -v 1.6.5

New Firefox and gem versions for our Selenium testing environment (Ubuntu 14.04+)

Firefox 5.0.1, which we were using for most Rails 2.3 projects, does not run on Ubuntu 14.04 any more. Here is how to update affected projects.

  1. Update (or create) .firefox-version with the content: 24.0
    If you haven't installed Firefox 24 yet, the next time you run tests with Geordi, it will tell you how to install it.

  2. On a Rails 2 project:

/usr/ports/converters/ruby-iconv This port is marked IGNORE

If you have this problem when you update your FreeBSD Ports:

===>>> Launching child to update ruby19-iconv-1.9.3.547,1 to ruby20-iconv-2.0.0.576,1

===>>> All >> ruby19-iconv-1.9.3.547,1 (17/17)

===>>> Currently installed version: ruby19-iconv-1.9.3.547,1
===>>> Port directory: /usr/ports/converters/ruby-iconv

	===>>> This port is marked IGNORE
	===>>> Not needed with Ruby 2.0 or newer


	===>>> If you are sure you can build it, remove the
	       IGNORE line in the Makefile and try again.

===>>> Update for ruby19-iconv-1.9.3.547,1 f...

bower-rails can rewrite your relative asset paths

The asset pipeline changes the paths of CSS files during precompilation. This opens a world of pain when CSS files reference images (like jQuery UI) or fonts (like webfont kits from Font Squirrel), since all those url(images/icon.png) will now point to a broken path.

In the past we have been using the vendor/asset-libs folder ...

When Sass-generated stylesheets print a Encoding::CompatibilityError

We upgraded a Rails 2 application to Rails 3.2 and Ruby 2.1, changed the mysql adapter from mysql to mysql2, but did not activitate the asset pipeline. Instead we used Sass the old-school way (stylesheets in public/sass/*.sass) and relied on stylesheet_link_tag to activate the Sass compiler.

Now all Sass-generated stylesheets inserted the following text into body:before:

Encoding::CompatibilityError: incompatible character encodings: UTF-8 and ASCII-8BIT

I could get rid of this by removing all generated .css files in `...

Chartkick

Create beautiful Javascript charts with one line of Ruby.

Promising chart library for easily rendering charts with Google Charts.

This seems to not submit your data points to Google.

Iterate over any enumerable with an index

tl;dr: Use with_index


ActiveRecord's find_each with index

If you do not provide a block to find_each, it will return an Enumerator for chaining with other methods:

Person.find_each.with_index do |person, index|
  person.award_trophy(index + 1)
end

Ruby's map with index

Similarly, you may need an index when using other methods, like map, flat_map, detect (when you need the index for detection), or similar. Here is an example for map:

people...

Wrapping Your API In A Custom Ruby Gem

Nice tutorial about packaging Ruby bindings to your API in a Ruby gem, with tests using VCR casettes.

Use a Bash function to alias the rake command to Spring binstubs or "bundle exec" fallback

There are different ways to run rake:

  • On Rails 4.1+ projects, you have Spring and its binstubs which dramatically improve boot-up time for Rake and similar. You need to run bin/rake to use them.
  • On older projects, you want to run "bundle exec rake" to avoid those ugly "already activated rake x.y.z" errors that hit you when different rake versions are installed for your current Ruby.

Here is a solution that gives you a plain rake command which uses a binstubbed bin/rake if available and falls back to bundle exec rake if necessar...

The Curious Case of the Flip-Flop

The flip-flop operator is a hotly contested feature of Ruby. It's still struggling to find an idiomatic use case, except for a few very rarely needed things. It's not something you'll likely reach for on a daily, weekly or even monthly basis. The only thing you really need to know about it is what it does, and that's only in case you encounter it in someone else's code. Many even go as far to say not to use the flip-flop operator, that it only adds confusion.

My brain just melted.

Using rbenv on Ubuntu 18.04+

We will be installing rbenv and ruby-build from our own fork, not from the Ubuntu sources.

Installing rbenv

  1. Install rbenv:

    git clone https://github.com/rbenv/rbenv.git ~/.rbenv
    

    For Bash:

    echo 'export PATH="$HOME/.rbenv/bin:$PATH"' >> ~/.bashrc
    echo 'eval "$(rbenv init -)"' >> ~/.bashrc
    

    For ZSH:

    echo 'export PATH="$HOME/.rbenv/bin:$PATH"' >> ~/.zshrc
    echo 'eval "$(rbenv init -)"' >> ~/.zshrc
    

    Now reinitialize ...

Ubuntu: Fix "An error occurred while installing pg"

If you get an error like this:

An error occurred while installing pg (0.17.1), and Bundler cannot continue.
Make sure that gem install pg -v '0.17.1' succeeds before bundling.

Then do this:

sudo apt-get install libpq-dev

... and run Bundler again.

Interacting with a Microsoft Exchange server from Ruby

Microsoft Exchange service administrators can enable Exchange Web Services (EWS) which is a rather accessible XML API for interacting with Exchange. This allows you to read and send e-mails, create appointments, invite meeting attendees, track responses, manage to-do tasks, check user availability and all other sorts of things that are usually only accessible from Outlook.

You can implement an EWS by hand-rolling your XML (the [docs](http://msdn.microsoft.com/en-us/...

Alternative for Ruby singletons

require 'net/http'

module Cheat
  extend self # the magic ingredient

  def host
    @host ||= 'http://cheat.errtheblog.com/'
  end

  def http
    @http ||= Net::HTTP.start(URI.parse(host).host)
  end

  def sheet(name)
    http.get("/s/#{name}").body
  end
end

# use it
Cheat.sheet 'migrations'
Cheat.sheet 'singletons'

Feedjira

Great gem to consume RSS feeds. I was missing some features on Ruby's RSS::Parser that I found in Feedjira:

  • Speed
  • Does not break on slightly malformed RSS feeds (like a missing length attribute on an <enclosure> tag on gizmodo.de's feed)
  • It automatically resolves Feedburner-mangled URLs (hooray!)

The GitHub project has only a minimalistic readme. You can find its documentation on their homepage.