user1431084
user1431084

Reputation:

module attr_accessor from another module

In Ruby, what's the correct way for a 'child' module to inherit attributes from a 'parent' module? It seems that if you define an attribute in one module and then extend that module and mixin the child module to a class, I should be able to access the attribute from the child module, but not having any luck...

module A 
  attr_accessor :foo
end

module B
  extend A

  def not_worky
    p "#{foo}"
  end
end

class C
  include B
end

class D
  include A
end

irb(main):027:0* d = D.new
irb(main):028:0> d.foo=> nil

irb(main):033:0* c = C.new
irb(main):034:0> c.foo
   NoMethodError: undefined method `foo' for #<C:0x553853eb>
irb(main):038:0> c.not_worky
   NameError: undefined local variable or method `foo' for #<C:0x553853eb>

Upvotes: 2

Views: 1172

Answers (2)

user1431084
user1431084

Reputation:

This was due to my own mis-understanding of what I was trying to do. Works as expected if I simply use the standard include mechanism. A more realistic example...

module App
  attr_accessor :log
  def initialize
    self.log = 'meh'
  end
end

module DB
  include App
  def go
    p log
  end
end

class Foo
  include DB
end

irb(main):002:0> f = Foo.new
       => #<Foo:0x7cece08c @log="meh">
irb(main):003:0> f.go
 "meh"

Upvotes: 1

sameera207
sameera207

Reputation: 16629

include is for adding instance methods and extends is for adding class methods. So you could do like this

B.foo #=>  nil

read more here and here

Upvotes: 0

Related Questions