Ruby replace weirdly encoded string without gsub

Having a bunch of files with weird encoding you need to replace something in ?
Pru to the rescue!
(because replacing with ruby-regex or sed leads to encoding exceptions)


find test -name "*" | pru 'return unless File.file?(self); c = File.read(self); s = "SEARCH"; r = "REPLACE"; while x = c.index(s) do; c.slice!(x,s.size); c.insert(x, r); end; File.write(self, c)'

Normal ruby:

String.class_eval do
  def string_sub(s,r)
    while x = index(s) do
      slice!(x,s.size)
      insert(x, r)
    end
    self
  end
end

Compiled Json for partially cached json response / precompiled handlebar templates

  • pull part of your json response from cache and do not pay for re-jsoning it
  • return precompiled handlebar templates as jsonp response

Usage

# fast response via precompiled parts
result = user.to_json
result["tickets"] = cache { CompiledJson.new(tickets.to_json) }
render :json => result

# handlebar templates or other crazyness
result = user.to_json
result["tickets"] = CompiledJson.new(
  'function(c){ return "foo" + c.name + "bar" }'
)
render :json => result

code

class CompiledJson < String
  # activesupport
  def encode_json(*args)
    self
  end

  # pure JSON
  def to_json
    self
  end
end

Logging and showing colorful bash output

Deploy using the deploy user and also log who deploys using the original user.
Retaining the color was tricky but script fakes tty so we can keep all the color glory and with sed we strip colors before logging them.

# /usr/bin/capsu
function log {
  old_IFS=$IFS
  IFS='' # do not split on newline when reading stdin
  newline=$'\n'
  line=""

  while read -d '' -n1 c # read every character
  do
    # print every character as it comes in for cap shell and password prompts
    printf "%s" "$c"

    # amend complete line with current user (but without color codes) to log
    # so multiple people can run capsu in parallel
    if [ "$c" = $newline ]; then
      echo "$SUDO_USER: $line" | sed -r "s/\x1B\[([0-9]{1,2}(;[0-9]{1,2})?)?[m|K]//g" >> $1
      line=""
    else
      line+=$c
    fi
  done
  IFS=$old_IFS
}

rvmsudo -u deploy script /dev/null -c "bundle exec cap $@" 2>&1 | log deploy cap.log