How can i check if a method exists in rails app controller?

In my application controller, I have a method that needs to check for the existence of another method in the subclass controller to set the filename of the uploaded file, but I'm having trouble fixing it.

I tried

def filename
  begin
    send "filename_method"
  rescue NoMethodError
    default_filename
  end
end

      

and

def filename
 if respond_to?("filename_method")
  send "filename_method"
 else
  default_filename
 end
end

      

but both always return default_filename even if filename_method is defined in the subclass controller. Can anyone point me in the right direction here?

Thank,

-C

0


a source to share


1 answer


I assume this is because the superclass of the controller class is unaware of the existence of the subclass methods. You can confirm this by checking the methods

subclass array .

The solution seems to be to rethink your design. Instead of checking for existence, filename_method

simply specify the default filename behavior in the base method filename

and override the method filename

in the subclass to provide custom filename functions.

For example, in your superclass:



def filename
  # return default file name 
end

      

And in your subclass:

def filename
  # return custom file name 
end

      

+2


a source







All Articles