Homme Sauvage
Homme Sauvage

Reputation: 1916

How to clear memory cache in Ruby?

I'm new to Ruby. I've got a rails application and I'm keeping site configuration (like site name) in the database. I've set up a helper so I can call: site_param 'site_name'. The helper stores the data in a variable so that the application doesn't hit the database on each call, here's how it looks:

module SiteHelper
  class Site
    def self.get(param)
      @params = {} unless @params.kind_of?(Hash)

      if @params[param].nil?
        new_param = Site.find(param)
        @params[param] = new_param
      end

      @params[param]
    end
  end
end

Now the problem is that once @params has stored a value, it doesn't refresh on the next request. Coming from a php background, this kind of singletons get refreshed at each request, so If I edit a value on the database, it gets refreshed without problems. In ruby, the @params is cached and keeps the same value until I restart the server. Is there a possible way to keep @params only for the request lifetime and refresh on the next?

Upvotes: 2

Views: 2970

Answers (1)

Simone Carletti
Simone Carletti

Reputation: 176372

The issue with your code is that you are using an instance variable in the context of a class, therefore it will persists as long as the process is running.

You need to convert #get to be an instance method, and reuse an instance of the Site class. What you wrote in Ruby was definitely not a singleton-like implementation.

module SiteHelper
  def site
    @site ||= Site.new
  end

  class Site
    def get(param)
      @params = {} unless @params.kind_of?(Hash)

      if @params[param].nil?
        new_param = Site.find(param)
        @params[param] = new_param
      end

      @params[param]
    end
  end
end

# In the view
site.get("whatever")

Your code can also be improved to be more ruby-style. Note the implementation of the #get, taking advantage of ||= and the return values.

module SiteHelper
  def site
    @site ||= Site.new
  end

  class Site
    def get(param)
      @params ||= {}
      @params[param] ||= Site.find(param)
    end
  end
end

Upvotes: 2

Related Questions