Answer the question
In order to leave comments, you need to log in
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_TAG
in 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
class UsersController < ApplicationController
def check_const
puts TAG
end
end
UsersController
displayed, but it is displayed ApplicationController
. Answer the question
In order to leave comments, you need to log in
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
Alas, it is impossible, but you can give different values for different call sources and this will already be a method, not a variable
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question