module ActionDispatch::Routing
  class Mapper
    def rulz_for(*resources, namespace: nil)
      if namespace
        constraints Rulz::Rails::RoutingConstraint.new(resources) do 
          get "#{namespace}/:resource/rules", to: "#{namespace}/rules#index"
          post "#{namespace}/:resource/rules", to: "#{namespace}/rules#create"
          get "#{namespace}/:resource/rules/new", to: "#{namespace}/rules#new"
          get "#{namespace}/:resource/rules/:id/edit", to: "#{namespace}/rules#edit"
          patch "#{namespace}/:resource/rules/:id", to: "#{namespace}/rules#update"
          put "#{namespace}/:resource/rules/:id", to: "#{namespace}/rules#update"
          delete "#{namespace}/:resource/rules/:id", to: "#{namespace}/rules#destroy"
        end                
      else
        constraints Rulz::Rails::RoutingConstraint.new(resources) do 
          get ':resource/rules', to: 'rules#index'
          post ':resource/rules', to: 'rules#create'        
          get ':resource/rules/new', to: 'rules#new'      
          get ':resource/rules/:id/edit', to: 'rules#edit'
          patch ':resource/rules/:id', to: 'rules#update'
          put ':resource/rules/:id', to: 'rules#update'
          delete ':resource/rules/:id', to: 'rules#destroy'
        end
      end
      Rails.application.class.routes.named_routes.module.module_eval do
        resources.each do |r|
          resource = namespace ? "#{namespace.gsub("/", "_").underscore}_#{r.to_s.singularize}" : r.to_s.singularize
          resource_path = namespace ? "#{namespace}/#{r}" : r.to_s
          define_method "#{resource}_rules_path" do
            "#{resource_path}/rules"
          end
          define_method "new_#{resource}_rule_path" do
            "#{resource_path}/rules/new"
          end
          define_method "edit_#{resource}_rule_path" do |id|
            "#{resource_path}/rules/#{id}/edit"
          end
          define_method "#{resource}_rule_path" do |id|
            "#{resource_path}/rules/#{id}"
          end        
        end
      end
    end
  end
end