module Schofield class RouteInfo def initialize route @route = route @requirements = @route.requirements end def use? admin_namespace? && @requirements.any? && @route.segments.length > 3 end def controller_name use? ? @requirements[:controller].gsub(/^admin\//, '') : nil end def controller_path "admin/#{controller_name}" end def model_name controller_name.singularize end def action_name use? ? @requirements[:action] : nil end def parent return unless use? segment = @route.segments[3].to_s.singularize segment == controller_name.singularize ? nil : segment end private def admin_namespace? @admin_namespace.nil? ? @admin_namespace = @route.segments[1].to_s == 'admin' : @admin_namespace end end class ControllerInfo attr_reader :parent, :controller_name, :controller_path, :model_name attr_accessor :actions, :children, :parents def initialize route_info @controller_name = route_info.controller_name @controller_path = route_info.controller_path @model_name = route_info.model_name @parent = route_info.parent @actions = [] @children = [] @parents = [] end end class Generator def initialize @controller_infos = {} end def process_routes ActionController::Routing::Routes.routes.each { |route| process_route(route) } end def process_route route route_info = RouteInfo.new(route) return unless route_info.use? @controller_infos[route_info.model_name] ||= ControllerInfo.new(route_info) @controller_infos[route_info.model_name].actions << route_info.action_name end def set_children @controller_infos.each do |index, info| @controller_infos[info.parent].children << index unless info.parent.nil? end end def set_parents @controller_infos.each do |index, info| parent_models = [] parent_model = info.parent while parent_model parent_models << parent_model parent_model = @controller_infos[parent_model].parent end info.parents = parent_models end end def generate process_routes set_children set_parents require 'rails_generator' require 'rails_generator/scripts/generate' @controller_infos.each do |index, info| Rails::Generator::Scripts::Generate.new.run(['schofield_controller', info.controller_path, *info.actions ], :parents => info.parents, :children => info.children) Rails::Generator::Scripts::Generate.new.run(['schofield_form', info.model_name], :partial => true, :haml => true, :controller => info.controller_path, :parents => info.parents) end end end end