Jordon Bedwell
Jordon Bedwell

Reputation: 3247

Ruby: Mock hash setter with class method?

Because of the way some piece of the application work (such as some pieces of Liquid not having access to instance variables) I want users to be able to access and set configuration variables in and out of the instance so right now I do:

module My_Module
  class My_Class
    attr_accessor :config

    def self.config
      @@config if @@config
    end

    def initialize(config)
      config[:root] = config[:root].rchomp('/')

      @@config = @config = {
        cache: 'flat',
        store: 'flat',
        plugins: 'plugins',
        pages: 'pages',
        posts: 'posts',
        static: 'static',
        templates: 'templates',
        destination: 'public' }

      @@config.deep_merge(config)
    end
  end
end

However that only gives them read only access, I was wondering if there was a way to mock hash My_Module::My_Class.config[:symbol] = value or if I should just make the setter have two attributes.

Upvotes: 0

Views: 263

Answers (1)

user47322
user47322

Reputation:

Why not just use a hash?

class MyClass
  def self.config
    @@config ||= {}
  end
end

That seems like it would achieve what you want

Upvotes: 2

Related Questions