I'm working implement vanity URLs based on the tutorial here: https://wesleyluyten.com/writing/vanity-urls-for-multiple-controllers-in-rails
To make vanity URLs work I need to use a rack router like so:
class SlugRouter
def self.to(action)
new(action)
end
def initialize(action)
@action = action
end
def call(env)
params = env['action_dispatch.request.path_parameters']
params[:action] = @action
sluggable = Slug.where('lower(url) = ?', params[:slug].downcase).first
model = sluggable.try(:sluggable_type)
raise ActionController::RoutingError.new('Not Found') if !model
controller = [model.pluralize.camelize,'Controller'].join
params[:controller] = model.pluralize.downcase
controller.constantize.action(params[:action]).call(env)
end
end
The problem is with raise ActionController::RoutingError.new('Not Found') if !model
this is not gracefully handling routing errors. How can I gracefully handle routing error by redirecting to root w a flash message vs what is happening now is rails is showing an error page w
ActionController::RoutingError (Not Found):
lib/slug_router.rb:14:in `call'