1
votes

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?

2

2 Answers

3
votes

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
0
votes

Wrap the polymorphic_path in a begin/rescue block. If you reach the rescue portion, you know there is no such path. Thus:

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