Inheritance and attr_accessor without initialize

I have a class like this:
class MyClass
class << self
attr_accessor :user, :password, :port, :ssl, :host

So I can use later for example:

That’s good for me… but now i need to create another one that is
inhering from this one… for example:
class MyOtherClass < MyClass; end

and now when i do something like:
what i get is nil instead of 345

How can i solve this?


Technically You can’t use this method in case of inheritance because
instance variables which was defined at the class level belongs only to
the object of this class. Thus in Your case all instance variables
belongs to the MyClass object, but not to any child object of the class.

One case to resolve it, I suppose is use ActiveSupport::Configurable
module in such manner:

require ‘active_support/configurable’
class MyClass
include ActiveSupport::Configurable

config.server = {
user: ‘pepe’,
password: “”,
port: 345,
ssl: true

def self.inherited child
child.config.server = config.server.dup

class MyOtherClass < MyClass

p MyClass.config.server[:port] # => 345
p MyOtherClass.config.server[:port] # => 345

MyOtherClass.config.server[:port] = 777

p MyClass.config.server[:port] # => 345
p MyOtherClass.config.server[:port] # => 777

This forum is not affiliated to the Ruby language, Ruby on Rails framework, nor any Ruby applications discussed here.

| Privacy Policy | Terms of Service | Remote Ruby Jobs