Skip to content

Instantly share code, notes, and snippets.

@israellias
Created May 14, 2018 21:41
Show Gist options
  • Save israellias/e60b6009a04a335a56ef9ee1fd3a6408 to your computer and use it in GitHub Desktop.
Save israellias/e60b6009a04a335a56ef9ee1fd3a6408 to your computer and use it in GitHub Desktop.
override handle_list method of ActionDispatch::Routing::PolymorphicRoutes::HelperMethodBuilder class
class ActionDispatch::Routing::PolymorphicRoutes::HelperMethodBuilder
# Extract from gems/actionpack-5.2.0/lib/action_dispatch/routing/polymorphic_routes.rb#HelperMethodBuilder class
# @param [Array] list
def handle_list(list)
record_list = list.dup
record = record_list.pop
args = []
route = record_list.map { |parent|
case parent
when Symbol, String
parent.to_s
when Class
args << parent
parent.model_name.singular_route_key
else
args << parent.to_model
parent.to_model.model_name.singular_route_key
end
}
record_path = case record
when Symbol, String
record.to_s
when Class
@key_strategy.call record.model_name
else
model = record.to_model
if model.persisted?
args << model
model.model_name.singular_route_key
else
@key_strategy.call model.model_name
end
end
# Custom here
# when an array of two models is gave
if list.size == 2 and list.all? {|o| o.is_a?(ActiveRecord::Base)}
first_module = extract_module list.shift
second_module = extract_module list.shift
if first_module == second_module
first_module = first_module.map(&:underscore).join('_')
record_path.slice!(first_module + '_')
end
end
route << record_path
# end of custom
route << suffix
named_route = prefix + route.join("_")
[named_route, args]
end
private
# @param [ActiveRecord] model
# @return [Array]
def extract_module(model)
modules = model.class.name.split('::')
modules.pop
modules
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment