Ruby True / False Comparison / sort with <=>

Using the Spaceship operator with TrueClass / FalseClass is not possible normally:

NoMethodError: undefined method '<=>' for true:TrueClass

But we can change this…

Code

module TrueFalseComparison
  def <=>(other)
    raise ArgumentError unless [TrueClass, FalseClass].include?(other.class)
    other ? (self ? 0 : -1) : (self ? 1 : 0)
  end
end

TrueClass.send(:include, TrueFalseComparison)
FalseClass.send(:include, TrueFalseComparison)

Usage

(true <=> false) == 1
(false <=> true) == -1
[true,false,true].sort == [false,true,true]
[true,'x'].sort -> ArgumentError

Open-uri without ssl / https verification

Usage

require 'open-uri'
require 'openssl'
OpenURI.without_ssl_verification do
  open('https://foo').read
end

Code

module OpenURI
  def self.without_ssl_verification
    old = ::OpenSSL::SSL::VERIFY_PEER
    silence_warnings{ ::OpenSSL::SSL.const_set :VERIFY_PEER, OpenSSL::SSL::VERIFY_NONE }
    yield
  ensure
    silence_warnings{ ::OpenSSL::SSL.const_set :VERIFY_PEER, old }
  end
end

If you are not in Rails you may need silence_warnings

Kill process in capistrano without pkill

Pkill has issues with capistrano, because the pkill command is always inside a capistrano command, thereby matching and killing itself.

pkill free solution

task :foo do
  kill_processes_matching "MaintenanceDaemon"
end

def kill_processes_matching(name)
  run "ps -ef | grep #{name} | grep -v grep | awk '{print $2}' | xargs kill || echo 'no process with name #{name} found'"
end

Prevent paths in mails (ActionMailer)

It happens once in a while, a path gets into a mail, but with this patch it should happen nevermore.

Looks for paths in non-production and raises if it finds one.


unless Rails.env.production?
  class ActionMailer::Base
    def render_message_with_path_protection(method_name, body)
      body = render_message_without_path_protection(method_name, body)
      if body =~ %r{((href|src)=['"]/.*)}
        raise "Use absolute path in mail urls! #{$1}"
      end
      body
    end

    alias_method_chain :render_message, :path_protection
  end
end