Snippet: Binary to YAML

Recently, I was looking for a piece of code that could easily convert a file to YAML data. Here is what I use now. It follows the format described in http://yaml.org/type/binary.html.

def binary_to_yaml(file, indent_level = 1)
  if File.exists?(file)
    indent = ""
    indent_level.times{ indent << " " }
    data = File.open(file,'rb').read
    #YAML Generic binary representation, see http://yaml.org/type/binary.html
    "!binary |\n#{indent}#{[data].pack('m').gsub(/\n/,"\n#{indent}")}\n"
  end
end

The indent level describes how many spaces should be prepended. A binary value for a key that is unnested should have indent level 1. See the example below:

user: # indent level 1
 name: John Doe # indent level 2
 address:
  street: Sunset Blvd # indent level 3
  number: 2034
 thumbnail: <%= binary_to_yaml('files/thumb.jpg',2) %> # indent level 2

user: # indent level 1
 name: Jane Doe # indent level 2
 ...

~ by moiristo on November 1, 2008.

Leave a Reply