Question

For stylistic reasons I would like to avoid using class variables and would like to replace them with class instance variables. So if I have:

module SimpleForm
  mattr_accessor :input_error_class
  @@input_error_class = 'error-field'
  ...
end

and I change it to:

module SimpleForm
  @input_error_class = 'error-field'
  class << self
    attr_accessor :input_error_class
  end
  ...
end

will this break Simple Form?

Was it helpful?

Solution

If there is a class that is a subclass or a superclass of SimpleForm that shared @@input_error_class, then by changing a class variable to a class instance variable, the variable will not be shared by the sub/superclass anymore, and that may break the code. Also, if there is an instance method that uses the class variable, that may break the code. Otherwise, it does not break.

OTHER TIPS

I'd say it should work but actually makes no difference as class variables. And class variables would be simpler to view in this case. :)

Since there is no instance generated, no thread safety would be gain. By this design you can neither change the behaviour at runtime because the variables are rather static after Rails loading.

Another practice, other than class variable, is to use ActiveSupport::Configuration module to generate configurations, or manually make such class without this module. But the configuration is still quite static after Rails loading.

My suggestion is, if you need to change that globally in your project, check if there is a configuration for such.

If you want to change it at runtime freely, better to look at other API instead of the configuration part.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top