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

Splitting 1 big CSV file into multiple smaller without parsing it

How to turn a 300mb csv into 3x100mb ?
Cut and slice with head/tail and add the header on top!
Code

require 'rake' # for `sh` helper

# split giga-csv into n smaller files
def split_csv(original, file_count)
  header_lines = 1
  lines = Integer(`cat #{original} | wc -l`) - header_lines
  lines_per_file = (lines / file_count.to_f).ceil + header_lines
  header = `head -n #{header_lines} #{original}`

  start = header_lines
  file_count.times.map do |i|
    finish = start + lines_per_file
    file = "#{original}-#{i}.csv"

    File.write(file, header)
    sh "tail -n #{lines - start} #{original} | head -n #{lines_per_file} >> #{file}"

    start = finish
    file
  end
end