0

I have a class in Ruby with some static initialization like this:

class Repository
  def self.my_static_setup
    ....
  end

  my_static_setup

  ...
end

The code above works fine, and my custom static initializer gets called, the problem is whenever I inherit this class:

class PersonRepository
  ...
end

The static initialization is not inherited, and therefore not called. What am I doing wrong?

2 Answers 2

4

@megar told correctly, why the issue you are having.

As per OP's comment:

I see it is not inherited, so I am trying to find a workaround to get self.my_static_setup called whenever I define subclasses.

I can then give you the below soltuion to things get work for you. See Class#inherited for the same, which is saying Callback invoked whenever a subclass of the current class is created.

class Repository
  def self.my_static_setup
    puts 'Hello!'
  end
  def self.inherited(subclass)
    my_static_setup
  end
end


class PersonRepository < Repository
  #...
end

# >> Hello!
Sign up to request clarification or add additional context in comments.

Comments

0

You're immediately invoking the method with my_static_setup. That part cannot be inherited, it's just code.

1 Comment

I see it is not inherited, so I am trying to find a workaround to get self.my_static_setup called whenever I define subclasses. I cannot find some type of self.class_initialize so I am not sure if the language support that

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.