Ngoral
Ngoral

Reputation: 4814

Routing Error Undefined method for Controller:Class

I am trying to use a rescue_from in my controller that is supposed to be abstract. I need to catch certain custom errors there, so I am trying to eval a string with a call to a method in rescue_from. Here is the code:

class Restream::MultipleDestinationsServicesController < Restream::BaseController
  rescue_from "Exceptions::#{self.class_name}Error",
    with: :show_error
  def self.class_name; controller_name.classify.constantize; end
end

That way I am getting

Routing Error
undefined method `class_name' for Restream::MultipleDestinationsServicesController:Class Did you mean? class_eval```

I do not clearly understand what is going wrong here, and so that can not understand what am I doing wrong.

Upvotes: 1

Views: 194

Answers (1)

Danil Speransky
Danil Speransky

Reputation: 30453

In Ruby what you write inside a class are instructions which are run one by one. "Exceptions::#{self.class_name}Error" is executed immediately, but self.class_name is not defined yet. So change the order:

def self.class_name
  controller_name.classify.constantize
end

rescue_from "Exceptions::#{self.class_name}Error", with: :show_error

Upvotes: 1

Related Questions