A
A
Anton Ivanov2020-03-09 07:00:48
ruby
Anton Ivanov, 2020-03-09 07:00:48

How in Rails, in the parent class, to define a constant so that the value is different for "children"?

Actually, the question is in the title.

I want to define a constant LOG_TAGin ApplicationController, but in such a way that in the controllers that inherit from it, its value would be calculated for each controller.

That is:

application_controller.rb:

class ApplicationController < ActionController::Base
  TAG = name
end


users_controller.rb:

class UsersController < ApplicationController
  def check_const
    puts TAG
  end
end


I want it to be UsersControllerdisplayed, but it is displayed ApplicationController.

Can I do it the way I want or not?
I know that you can define a method in the ApplicationController, but I want it to be a constant.

Thanks

Answer the question

In order to leave comments, you need to log in

3 answer(s)
G
GeneAYak, 2020-03-10
@Fly3110

you can use the inheritance hook and set the constant dynamically in each class that inherits from the parent

class ApplicationController
  def self.inherited(child_class)
    const_set("TAG", child_class.name)
  end
end

class UsersController < ApplicationController
  def check_const
    puts TAG
  end
end

UsersController.new.check_const # => UsersController

V
Vayladion Gognazdiak, 2020-03-09
@etspring

Alas, it is impossible, but you can give different values ​​​​for different call sources and this will already be a method, not a variable

V
vsuhachev, 2020-03-16
@vsuhachev

class_attribute

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question