require 'rails/generators' class ZenboxGenerator < Rails::Generators::Base class_option :api_key, :aliases => "-k", :type => :string, :desc => "Your Zenbox API key" class_option :heroku, :type => :boolean, :desc => "Use the Heroku addon to provide your Zenbox API key" class_option :app, :aliases => "-a", :type => :string, :desc => "Your Heroku app name (only required if deploying to >1 Heroku app)" def self.source_root @_zenbox_source_root ||= File.expand_path("../../../../../generators/zenbox/templates", __FILE__) end def install ensure_api_key_was_configured ensure_plugin_is_not_present append_capistrano_hook generate_initializer unless api_key_configured? determine_api_key if heroku? test_zenbox end private def ensure_api_key_was_configured if !options[:api_key] && !options[:heroku] && !api_key_configured? puts "Must pass --api-key or --heroku or create config/initializers/zenbox.rb" exit end end def ensure_plugin_is_not_present if plugin_is_present? puts "You must first remove the zenbox plugin. Please run: script/plugin remove zenbox" exit end end def append_capistrano_hook if File.exists?('config/deploy.rb') && File.exists?('Capfile') append_file('config/deploy.rb', <<-HOOK) require './config/boot' require 'zenbox/capistrano' HOOK end end def api_key_expression s = if options[:api_key] "'#{options[:api_key]}'" elsif options[:heroku] "ENV['ZENBOX_API_KEY']" end end def generate_initializer template 'initializer.rb', 'config/initializers/zenbox.rb' end def determine_api_key puts "Attempting to determine your API key from Heroku..." ENV['ZENBOX_API_KEY'] = heroku_api_key if ENV['ZENBOX_API_KEY'].blank? puts "... Failed." puts "WARNING: We were unable to detect the Zenbox API key from your Heroku environment." puts "Your Heroku application environment may not be configured correctly." exit 1 else puts "... Done." puts "Heroku's Zenbox API key is '#{ENV['ZENBOX_API_KEY']}'" end end def heroku_var(var,app_name = nil) app = app_name ? "--app #{app_name}" : '' `heroku config #{app} | grep -E "#{var.upcase}" | awk '{ print $3; }'`.strip end def heroku_api_key heroku_var("zenbox_api_key",options[:app]).split.find {|x| x unless x.blank?} end def heroku? options[:heroku] || system("grep ZENBOX_API_KEY config/initializers/zenbox.rb") || system("grep ZENBOX_API_KEY config/environment.rb") end def api_key_configured? File.exists?('config/initializers/zenbox.rb') end def test_zenbox run("rake zenbox:test --trace") end def plugin_is_present? File.exists?('vendor/plugins/zenbox') end end