Switching form Public Domain to MIT

All my new projects will be released under MIT / those I work on will be switched, which will still means the same as before: Do wtf you want with this code, no need for any naming/license copying.

After reading some articles I realized that public domain does not always work since some countries do not allow it and its also unclear what happens when the code causes problems <-> lawsuit.

Ill also try to add a s.license = ‘MIT’ to all gemspecs, to make license management easier.

Ruby Money vs nil — aka undefined method `round’ for nil:NilClass

Problem
When using composed_of with Money you get this nice error when trying to get the money object while the cents column is nil.
Additionally Money.new(nil) does not work, neither do strings like Money.new(params[:cents]).

Solution
Overwrite the initializer to also accept nil and strings

# config/initializers/money.rb
require 'money'
class Money
  def initialize_with_default_currency(*args)
    args[0] = args[0].to_i if args[0].is_a?(String) or args[0].blank?
    args[1] ||= Money.default_currency
    initialize_without_default_currency(*args)
  end
  alias_method_chain :initialize, :default_currency
end

rake version:bump:patch in the age of bundler gemspecs

A great timesaver in jeweler is rake version:bump:xxx, it bumps the version and commits the result. After switching my project-template to bundler, I kind of missed it … so I made a standalone version 🙂

The Gist of it…

# extracted from https://github.com/grosser/project_template
rule /^version:bump:.*/ do |t|
  sh "git status | grep 'nothing to commit'" # ensure we are not dirty
  index = ['major', 'minor','patch'].index(t.name.split(':').last)
  file = 'lib/GEM_NAME/version.rb'

  version_file = File.read(file)
  old_version, *version_parts = version_file.match(/(\d+)\.(\d+)\.(\d+)/).to_a
  version_parts[index] = version_parts[index].to_i + 1
  version_parts[2] = 0 if index < 2
  version_parts[1] = 0 if index < 1
  new_version = version_parts * '.'
  File.open(file,'w'){|f| f.write(version_file.sub(old_version, new_version)) }

  sh "bundle && git add #{file} Gemfile.lock && git commit -m 'bump version to #{new_version}'"
end

Ruby: Converting html colors (24bit) to xterm/terminal colors

Convert nice html color codes into terminal colors
e.g. to make ruco colorful 😀

    COLOR_SOURCE_VALUES = 256
    COLOR_TARGET_VALUES = 5
    COLOR_DIVIDE = COLOR_SOURCE_VALUES / COLOR_TARGET_VALUES
    TERM_COLOR_BASE = 16

    # '#ff0000' => 196
    def self.html_to_terminal_color(html_color)
      return unless html_color
      r = (html_color[1..2].to_i(16) / COLOR_DIVIDE) * 36
      g = (html_color[3..4].to_i(16) / COLOR_DIVIDE) * 6
      b = (html_color[5..6].to_i(16) / COLOR_DIVIDE) * 1
      TERM_COLOR_BASE + r + g + b
    end