Home > Blockchain >  How to check where currently used controller inherits from?
How to check where currently used controller inherits from?

Time:09-07

In my Rails 7 application I've got two controllers:

class Context::FrontendController < ApplicationController
end

class Context::BackendController < ApplicationController
end

All my other controllers (and there are a lot of them) inherit from either the first one or the second one (but never both).


In my views I sometimes need to show or hide certain elements depending on if the current controller inherits from the FrontendController OR the BackendController.

How can this check be done?

CodePudding user response:

In my views I sometimes need to show or hide certain elements depending on if the current controller inherits from the FrontendController OR the BackendController.

How can this check be done?

You can do this check (as shown by @mechnicov), but you shouldn't. Instead, use OOP.

class ApplicationController
  def current_area
    # raise NotImplementedError
    :none
  end
  helper_method :current_area
end

class FrontendController < ApplicationController
  def current_area
    :frontend
  end
end

class BackendController < ApplicationController
  def current_area
    :backend
  end
end

Then

<% if current_area == :frontend %>

You can prettify this as you wish (make methods frontend? / backend?, etc.)

CodePudding user response:

In your view you can use something like

<% if controller.class.ancestors.include?(Context::BackendController) %>
  <%= show.some.content %>
<% end %>

May be create some helper

def inherited_from?(controller_class)
  controller.class.ancestors.include?(controller_class)
end

And then

<% if inherited_from?(Context::BackendController) %>
  <%= show.some.content %>
<% end %>
  • Related