0

Here is a runnable test to see the situation

require 'active_support'
module MyModule
  extend ActiveSupport::Concern
  included do
    cattr_accessor :value
  end
end

class A
  include MyModule
  self.value = 'a'
end

class B < A
  self.value = 'b'
end

class C < A
  self.value = 'c'
end

puts A.value
puts B.value
puts C.value

the output is:

$ ruby test.rb
c
c
c

Now, I'd think the output should be

a
b
c

but it's all just whatever was set last.

If I move the include to class B and C and have class A not include the module, then I get the desired output... but then I have includes everywhere... so I feel like this is an issue with my cattr_accessor usage?

Why is this, and how do I achieve the desired functionality?

NullVoxPopuli
  • 61,906
  • 73
  • 206
  • 352
  • No, you created a shared class variable and the output you are getting due to that fact. Look the examples http://apidock.com/rails/Module/mattr_accessor – Arup Rakshit Feb 23 '16 at 04:59
  • See Chuck's answer here: http://stackoverflow.com/questions/10594444/class-variables-in-ruby – Frederick Cheung Feb 23 '16 at 08:18
  • here is how I fixed this:https://github.com/NullVoxPopuli/skinny_controllers/commit/791889ec54df36f02635b7c3725f5a6c808bb166 – NullVoxPopuli Feb 23 '16 at 11:58

1 Answers1

0

from reddit user ctcherry:

Instead of cattr_accessor try this:

class << self
  attr_accessor :foo
end

Good information about what is going on here: http://apidock.com/rails/Class/cattr_accessor

NullVoxPopuli
  • 61,906
  • 73
  • 206
  • 352