desc 'Print out all defined routes in match order, with names, in the JSON format expected by Trace.'
task traceroutes: :environment do
  require 'json'
  output = {
    svc: "code.justin.tv/web/web",
    routes: Array.new
  }

  Rails.application.routes.routes.each do |route|
    if methods(route).empty?
      output[:routes] << {
        pattern: route.path.spec.to_s,
        name: routename(route),
        method: ""
      }      
    else 
      methods(route).each do |method|
        output[:routes] << {
          pattern: route.path.spec.to_s,
          name: routename(route),
          method: method
        }
      end
    end
  end

  File.open("rails.json", "w") do |f|
    f.write(JSON.pretty_generate(output))
  end
end

def controller(route)
  return route.requirements[:controller] || ":unknown"
end

def action(route)
  return route.requirements[:action] || ":unknown"
end

def routename(route)
  if route.requirements[:controller] == nil && route.requirements[:action] == nil
    return route.path.spec.to_s
  end
  return controller(route) + "#" + action(route)
end

def methods(route)
  return route.verb.source.gsub(/[$^]/, '').split('|')
end
