require 'rails/generators'
require 'rails/generators/generated_attribute'
module BjController
  module Generators
    class SpecGenerator < ::Rails::Generators::Base
      source_root File.expand_path('../templates', __FILE__)
      argument :controller_name,         :type => :string, :required => true

      def copy_views
        generate_views
      end
    protected
      def generate_views
        template 'controller_spec.rb', File.join('spec/controllers', controller_namespace_path, "#{controller_base_name}_controller_spec.rb")
      end
      def controller_namespace_path
        controller_name.sub(/[^\/]+\Z/, '')
      end

      def model_plural_name
        controller_base_name
      end
      def model_name
        model_plural_name.singularize
      end

      def controller_base_name
        controller_name.split('/').last.pluralize
      end

      def controller_class_name
        "#{controller_name.classify.pluralize}Controller"
      end

      def required_attribute_name
        m = model_name.classify.constantize
        m.validators.find{|v| v.is_a? ActiveModel::Validations::PresenceValidator }.try(:attributes).try(:first) || m.property_names.find{|k| k !~ /(_id|_at)$/}
      end
    end
  end
end
