YAML to Ruby hash to CoffeeScript object

In one of my projects I found myself in the odd position where I had data in a YAML file, that needed some processing done on and then being inserted into a CoffeeScript file.

Now I could’ve just done a YAML to JSON conversion, but seeing as I had the intermediate Ruby processing steps and because I really wanted the output to be CoffeeScript as I was likely to have to work and manipulate it further later anyway, and would want to make changes to the CS directly instead of parsing the whole beast again.

So after loading the YAML into a Ruby hash and manipulating it appropriately I needed to do the conversion to CoffeeScript.

This is my solution

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
      defaultProc = Proc.new do |output|
        print output
      end

      #input is a Ruby hash
      #spaces is a prefix string of spaces used for whitespace significance
      #proc acts on the output
      def HashToCS.convert(input, spaces, proc=defaultProc)
        if input.is_a? String
          proc.call spaces + '"' + input + '"' + "\n"
        elsif input.is_a? Array
          proc.call spaces + "[\n"
          input.each do |a|
            convert(a, spaces + "  ", proc)
          end
          proc.call spaces + "]\n"
        elsif input.is_a? Hash
          proc.call spaces + "{\n"
          input.each do |k, v|
            proc.call spaces + "  #{k}:\n"
            convert(v, spaces + "    ", proc)
          end
          proc.call spaces + "}\n"
        else
          proc.call spaces + input.to_s + "\n"
        end
      end

usage:

1
2
3
4
5
    proc = Proc.new do |output| 
      coffee_script_file.puts output
    end

    HashToCs.convert(ruby_hash, "", proc)

I am using it from a rather intricate Thor script to create a data file for my coffeescript app to act on.
More on using Thor to manage intricate application builds in a later post.