never_had_a_name
never_had_a_name

Reputation: 93306

attr_accessor for class question

I thought it was possible to define attr_accessor methods in a eigenclass like this:

class IOS
  @@modules_paths = "hello"

  class << self
    attr_accessor :modules_paths
  end

end

puts IOS::modules_paths

But this returns nothing.

Is there a way to do it?

Upvotes: 0

Views: 1320

Answers (2)

J&#246;rg W Mittag
J&#246;rg W Mittag

Reputation: 369624

You never call the IOS::modules_paths= setter method, nor do you assign to the corresponding @modules_paths instance variable anywhere. Therefore, @modules_paths is unitialized and thus IOS.modules_paths returns an unitialized variable. In Ruby, uninitialized variables evaluate to nil and puts nil prints nothing.

Upvotes: 1

Matchu
Matchu

Reputation: 85862

The attr_accessor you add to the class uses class-level instance variables, not class variables. This can actually be more helpful in some cases, since class variables can get ridiculous when inheritance enters the picture.

class IOS
  @modules_paths = "hello"

  class << self
    attr_accessor :modules_paths
  end
end

puts IOS::modules_paths # outputs "hello"

If you really need it to use class variables, you can define the methods manually, pull in ActiveSupport and use cattr_accessor, or just copy the relevant ActiveSupport methods.

Upvotes: 6

Related Questions