Guido Guido - 6 months ago 38
Ruby Question

Check if path exists from object in Ruby on Rails

I am creating a class to render lists in active admin and I would like to do like this, given any object:

class ListGenerator
def initialize(array_of_objects)
@objects = array_of_objects
generate_list
end

def generate_list
ul do
@objects.each do |object|
if has_show_path_for(object)
li link_to object.name, polymorphic_path([:admin, object]
else
li object.name
end
end
end
end


This is just a sample code to explain the idea. How do I create
has_show_path_for
the method? When using
polymorphic_path
and the path exists, it returns the path. But in case it does not exist, it returns a nomethod error.

Any ideas on how to check if a path exists dynamically like that?

Answer

There are url helpers to determine if a path is actually defined

if Rails.application.routes.url_helpers.method_defined?(:my_path)

However, this may be problematic since you seem to be checking polymorphic paths. Using a simple begin/rescue would work out well here.

def generate_list
    ul do
       @objects.each do |object|
           begin
               li link_to object.name, polymorphic_path([:admin, object])
           rescue NoMethodError
               li object.name
           end
    end          
end

or, an even shorter version...

def generate_list
    ul do
       @objects.each do |object|
           li link_to(object.name, polymorphic_path([:admin, object])) rescue object.name
    end          
end