##
# NOTE: Untested with Rails 3
#
# Dynamically combines and caches multiple JavaScript files.
#
# Assumes that the "public/javascripts" directory contains
# subdirectories with files to serve together (or symlinks to those
# files).
#
# Example:
#   public/javascripts/
#                      staff/
#                            01-jquery.js -> ./shared/jquery.min.js
#                            02-graphs.js
#                            03-staff.js
#
# Will be served and cached as javascripts/staff.js

class JavascriptsController < ActionController::Base

  caches_page

  ##
  # Rails 3 route:
  #
  #   match "/javascripts/:action.:format", :to => "javascripts#bundle"

  def bundle
    respond_to do |format|
      format.js {
        render_directory_contents
      }
    end
  end

  private

  ##
  # Combines files in a directory and serves as a single file.

  def render_directory_contents
    asset_path = Rails.root.join("public",
                                 File.dirname(request.path_info),
                                 action_name)
    if (!File.directory?(asset_path))
      return
    end
    asset_contents = []
    Dir["#{asset_path}/*.#{params[:format]}"].each do |file_path|
      asset_contents << File.readlines(file_path)
      asset_contents << "\n\n"
    end
    render :text => asset_contents.flatten
  end

end

