class JfsScaffoldGenerator < Rails::Generator::Base attr_accessor :name, :attributes, :controller_actions def initialize(runtime_args, runtime_options = {}) super usage if @args.empty? @name = @args.first @controller_actions = %w[index new create show edit update destroy] @attributes = [] @args[1..-1].each do |arg| @attributes << Rails::Generator::GeneratedAttribute.new(*arg.split(":")) end @attributes.uniq! end def manifest record do |m| # generate views m.directory "app/views/#{plural_name}" controller_actions.each do |action| if File.exist? source_path("views/#{action}.html.erb") m.template "views/#{action}.html.erb", "app/views/#{plural_name}/#{action}.html.erb" end end m.template "views/_fields.html.erb", "app/views/#{plural_name}/_fields.html.erb" m.template "views/_resource.html.erb", "app/views/#{plural_name}/_#{singular_name}.html.erb" m.directory 'config/locales' m.template 'en.yml', "config/locales/en.#{plural_name}.yml" # generate controller m.directory 'app/controllers' m.template 'controller.rb', "app/controllers/#{plural_name}_controller.rb" m.directory 'app/helpers' m.template 'helper.rb', "app/helpers/#{plural_name}_helper.rb" m.route_resources plural_name m.dependency 'jfs_model', [@name] + (@attributes.map { |attribute| "#{attribute.name}:#{attribute.type}" }), :collision => :skip end end def class_name singular_name.camelize end def plural_class_name plural_name.camelize end def plural_name name.underscore.pluralize end def singular_name name.underscore.singularize end def is_action_included?(name) controller_actions.include? name.to_s end def gen_attr_accessible(attribute) case attribute.type.to_sym when :belongs_to "attr_accessible :#{attribute.name}_id" else "attr_accessible :#{attribute.name}" end end def gen_controller_methods controller_actions.map do |action| if File.exists? source_path("actions/#{action}.rb") read_template("actions/#{action}.rb") else "\n def #{action}\n end\n" end end.join('') end protected def read_template(relative_path) ERB.new(File.read(source_path(relative_path)), nil, '-').result(binding) end def add_options!(opt) opt.separator '' opt.separator 'Options:' opt.on("--no-xml", "Don't generate xml output for controller actions.") { |v| options[:no_xml] = v } opt.on("--no-json", "Don't generate json output for controller actions.") { |v| options[:no_json] = v } end def banner "Usage: #{$0} #{spec.name} ModelName [controller_actions and model:attributes] [options]" end end