Access to the included class protected constant in ActiveSupport :: Concern

What is the easiest way to access a class protected constant in the context of ActiveSupport :: Concern?

Class examples:

module Printable extend ActiveSupport::Concern private def print_constant puts MY_CONSTANT end end class Printer include Printable def print print_constant end private MY_CONSTANT = 'Hello'.freeze end 

This solution creates an error:

 NameError: uninitialized constant Printable::MY_CONSTANT 

I know an alternative that seems to work:

 puts self.class::MY_CONSTANT 

But this is not so. :-)

Any best deals?

+6
source share
2 answers

First of all, you should put #print_constant in the included block:

 module Printable extend ActiveSupport::Concern included do private def print_constant puts MY_CONSTANT end end end 

Now there are at least two ways to access the constant of the MY_CONSTANT class:

  • #included gives a base parameter similar to Ruby's #included parameter:

     module Printable extend ActiveSupport::Concern included do |base| private define_method :print_constant do puts base::MY_CONSTANT end end end 
  • Another method comes from self.class :

     module Printable extend ActiveSupport::Concern included do private def print_constant puts self.class::MY_CONSTANT end end end 

ActiveSupport Group Documentation

+5
source

Accessing an included class constant from a problem is not a really good idea.

An anxiety should not have (too much) knowledge about the classes in which it is included.

I would go to the general API in the concern and redefine when necessary ... like this:

 module Printable extend ActiveSupport::Concern private def print puts "" end end class Printer include Printable def print MY_CONSTANT end private MY_CONSTANT = 'Hello'.freeze end 
0
source

Source: https://habr.com/ru/post/976053/


All Articles