Blankman
Blankman

Reputation: 267160

initializing a class with config (yaml), and setting a variable that should be a single instance

I am getting confused as to how to properly set variables in a initializer, I want these to be class level variables, not instance.

And I also want to then create a single instance of another object (it is a connection object, which already has connection pooling built in, so I just need a single reference to it).

My initializer /initializers/my_class.rb

yml = YAML.load_file("#{Rails.root}/config/my_class.yml")

MYMODULE::MyClass.init(yml)

And here is my my_class.rb:

module MYMODULE
  class MyClass
    def self.init(yml)
      @post_url = yml["defaults"]["post_url"]
    end

    def self.post_url
      @post_url
    end

    # this should be a single instance
    def connection_pool
      # ???
    end
  end
end
  1. These class level variables, how can I access them from both class methods and instance methods?

I'm getting wierd behaviour, and I'm confused as to how to reference the post_url from inside of either class methods and instance methods.

I have seen the following ways, unsure which is correct:

self.class.post_url
MyClass.post_url
@post_url
post_url
self.post_url

Upvotes: 0

Views: 715

Answers (1)

Austin Taylor
Austin Taylor

Reputation: 5477

self.class.post_url or MyClass.post_url will work. The difference is how they work for subclasses (in the former case, subclasses will use their own version of this variable automatically, in the latter, they would share the variable in MyClass).

There is no way to directly access class instance variables from an instance: you have to call a class method which returns (or sets) them. See also: cattr_accessor.

That said, if this is really a singleton, it seems a little strange to me that you would configure part of it on the class, and then reference that info in the (single) instance. Wouldn't it make more sense just to configure this stuff on the instance? Or use a module as a singleton and not create an instance at all?

Upvotes: 1

Related Questions