2

I have a simple class used to store configuration for default images:

class DefaultImages

  class <<self
    attr_accessor :format
    attr_accessor :directory
    attr_accessor :width
    attr_accessor :height
  end

  def self.setup
    yield self
  end
end

I populate it in an initializer:

DefaultImages.setup do |config|
  config.format = :png
  config.directory = 'default'
  config.width = 2161
  config.height = 1441
end

If I log the attributes here in the accessor, all are populated:

Rails.logger.warn "Default Image Format: #{DefaultImages.format}" # png

However, when I access the attributes of DefaultImages later in the application, they are all nil. The same is true if I access its attributes from the console.

There is no other code that touches DefaultImages other than to access its attributes after the initializer has run. I have obviously restarted the server etc.

Why might its attributes be nil?

1
  • What happens if you assign the variable outside of setup. So just DefaultImages.format = :png etc.? I wonder if the settings are being lost outside of the scope of the block. Commented Aug 14, 2015 at 9:24

2 Answers 2

4

You need to include a Singleton module in your class:

require 'singleton'

class DefaultImages
  include Singleton

  class <<self
    attr_accessor :format
    attr_accessor :directory
    attr_accessor :width
    attr_accessor :height
  end

  def self.setup
    yield self
  end
end
Sign up to request clarification or add additional context in comments.

3 Comments

Thanks. Is this a valid approach for what I'm trying to do?
If you are using Rails 4.2, i would suggest to keep such settings in yaml config files. You can read more about it here: justinweiss.com/blog/2014/08/25/…
Thanks. I hadn't see that. But these aren't environment-specific settings, and I'm probably going to add class methods to this class down the way, so I prefer this approach.
1

So the problem is the class reloading which is switched off in development. This means that classes are reloaded when the browser is refreshed, meaning state stored on those classes is blown away.

Comments

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.