So there should be a class called Registers::Internal::Routes with a class method called draw that takes a block as a parameter:
def self.draw(&block)
...
end
It should be possible to pass the structures of the routes in this block. Example:
Registers::Internal::Routes.draw do
namespace :api do
namespace :internal do
namespace :companies do
resources :registrations, only: [:index, :show] do
post :request
member do
post :cancel
end
resources :bank_accounts, only: :index
end
end
end
end
end
it should be possible to acquire the URL of the routes, for example:
Registers::Internal::Routes.api_internal_companies_registrations_url
# api/internal/companies/registrations
Registers::Internal::Routes.api_internal_companies_registration_url("aef54ea9-239c-42c7-aee7-670a0d454f1d")
# api/internal/companies/registrations/aef54ea9-239c-42c7-aee7-670a0d454f1d
Registers::Internal::Routes.api_internal_companies_registrations_request_url
# api/internal/companies/registrations/request
Registers::Internal::Routes.api_internal_companies_registration_cancel_url("aef54ea9-239c-42c7-aee7-670a0d454f1d")
# api/internal/companies/registrations/aef54ea9-239c-42c7-aee7-670a0d454f1d/cancel
Registers::Internal::Routes.api_internal_companies_registration_bank_accounts_url("aef54ea9-239c-42c7-aee7-670a0d454f1d")
# api/internal/companies/registrations/aef54ea9-239c-42c7-aee7-670a0d454f1d/bank_accounts
So after playing a bit with this, i "managed" to try to generate an "url" everytime the namespace/resources/member/post method is called, the problem is that the "url" variable doesnt reset, therefore resulting in it being overwritten. Is there any other way to do this, simple and cleaner?
module Registers
module Internal
class Routes
def self.draw(&block)
@url = ""
class_eval(&block)
end
def self.namespace(key, &block)
generate_url("namespace", key)
class_eval(&block)
end
def self.resources(key, options, &block)
generate_url("resources", key, options)
class_eval(&block) if block_given?
end
def self.member(&block)
class_eval(&block)
end
def self.post(action)
generate_url("action", action)
end
def self.generate_url(name, key, options = nil)
if name != "action"
@url << "#{key.to_s + '/'}"
else
@url << "/#{key.to_s}"
define_class_method(@url)
end
set_options(options) if options.present?
end
def self.set_options(options)
Array(options[:only]).each do |option|
case option
when :index
@url.chop!
when :show
@url
end
define_class_method(@url)
end
end
def self.define_class_method(url)
method_name = "#{url.gsub('/', '_')}_url".to_sym
self.class.instance_eval do
define_method(method_name) do
url
end
end
end
end
end
end