require 'generators/rspec_rails3_gen_base' # ================== # TODO: Make hooks for other generators work!!! # see 'hook_for' # ================== module RSpec module Generators class ControllerGenerator < NamedBase argument :controller_actions, :type => :array, :default => [], :required => false, :banner => 'controller_actions' check_class_collision :suffix => "Controller" # attr_accessor :actions no_tasks { attr_accessor :actions } class_option :singleton, :type => :boolean, :desc => "Supply to create a singleton controller" def self.source_root @source_root ||= File.expand_path('../templates', __FILE__) end def initialize(*args, &block) super @actions = [] controller_actions.each do |arg| @actions << arg @actions << 'create' if arg == 'new' @actions << 'update' if arg == 'edit' end @actions.uniq! if @actions.empty? @actions = all_actions - @actions end end def create_files # Check for class naming collisions. class_collisions class_path, "#{class_name}Controller", "#{class_name}Helper" @default_file_extension = "erb" # Controller, helper, views, and spec directories. inside 'app' do empty_directory 'controllers' empty_directory 'helpers' empty_directory 'views' end # use hooks instead! # template 'controller.rb', File.join('app/controllers', class_path, "#{file_name}_controller.rb") # template 'helper.rb', File.join('app/helpers', class_path, "#{file_name}_helper.rb") html_actions = actions.reject{|a| %w{create update}.include?(a)} # # html_actions.each do |action| # @action = action # template "views/#{@default_file_extension}/#{action}.html.#{@default_file_extension}", "app/views/#{action}.html.#{@default_file_extension}" # # # add '_form' view for new or update action # if %w{edit new}.include?(action) # template "views/#{@default_file_extension}/_form.html.#{@default_file_extension}", "app/views/_form.html.#{@default_file_extension}" # end # end # spec inside 'spec' do empty_directory 'controllers' empty_directory 'helpers' empty_directory 'views' end # Controller spec, class, and helper. template 'controller_spec.rb', File.join('spec/controllers', class_path, "#{file_name}_controller_spec.rb") template 'helper_spec.rb.t', File.join('spec/helpers', class_path, "#{file_name}_helper_spec.rb") # Spec and view template for each action. html_actions.each do |action| @action = action target_file = "spec/views/#{file_name}/actions/#{action}_html_#{@default_file_extension}_spec.rb" puts target_file template 'view_spec.rb', target_file end end # hook into controller and helper generators to have them execute using same arguments! # hook_for :controller, :helper no_tasks do def all_actions %w[index show new create edit update destroy] end def current_action @action || 'unknown' end def action?(name) actions.include? name.to_s end def actions?(*names) names.all? { |name| action? name } end def class_name name.camelize end def plural_class_name plural_name.camelize end end end # class end # generators end # rspec