0

I have a module that has multiple class variables. I'm looking for a class level getter implementation that will only instantiate the @@ variable when the class tries to access it like the following

    module MyProducts
      @@products = nil

      def self.get_product(id)
        # i'm looking for a way that the first call on @@products does a find via AR                 like the following
        # @@products = Product.all
        # this module is in the lib directory of a Rails 2.3.5 app
        @@products.find do |prod|
          prod.id.eql?(id)
        end
      end
    end

I'm looking for this to be transparent so that i don't have to modify the whole module. There are about 10 class level variables with similar functions, all the results of an ActiveRecord .find call

Andrew Grimm
  • 78,473
  • 57
  • 200
  • 338
kwbock
  • 647
  • 5
  • 13

2 Answers2

0

Just use the ||= operator. It would evaluate the right expression only if the right part is nil or false

def foo
  @@any ||= some_value
end

The first time you call the method it will initialize the variable with the result of some_value, and following calls will return the @@any value with no need of recomputing some_value.

Update

Here it's a little script which shows you how to do that. If you execute that you'll see that the method complex_function is called once since the two print statements both returns 1. However from your comment I see that your Product is an active record, so don't use this approach for what your asking for, it will be very inefficient (read the last part of my answer)

#!/usr/bin/env ruby

module Foo
  def self.products
    @@products ||=complex_function
  end

  @@a = 0

  def self.complex_function
    @@a += 1
  end
end

p Foo.products
p Foo.products

Update end

However your approach to save Product.all is pretty inefficient:

  • First it will fetch all the products in the database which could consume a lot of memory when you have lot of products
  • Second your iteration code will be much slower than the db when you have a lot of products

Replace your whole method with a Product.find(id) call.

If your Product model isn't stored in the db (maybe an ActiveResource) ignore my previous comment.

You could also take a look to mattr_accessor and this SO question Difference between mattr_accessor and cattr_accessor in ActiveSupport?

Finally also take a look to this article which explains the above technique called memoization

Community
  • 1
  • 1
Fabio
  • 18,856
  • 9
  • 82
  • 114
  • i'm looking for something like that but rails (v2.3.5) doesn't know how to resolve Product.all when it loads the library on startup. I'm trying to resolve this because it makes development a pain because it populates the @@products array w/ the products but i can't traverse the relationships in development mode. I don't know if it's possible but i was looking for something along the lines of a function, similar to if it was just an instance variable where i could do def MyModule.@@products @@products ||= Products.all end sorry if the formatting doesn't work – kwbock Sep 22 '11 at 22:36
  • @grizzgreen I've updated my answer with a full example. However **don't** do this for ActiveRecord classes. Use AR finders, or if you need complex queries use [named_scopes](http://api.rubyonrails.org/classes/ActiveRecord/NamedScope/ClassMethods.html) with lambdas – Fabio Sep 22 '11 at 22:55
  • Yeah, i know not to do this for AR classes unfortunately I didn't write this code and I have a very short timeframe to complete this demo (the app was mothballed for 3 years). If I converted the functions that are called elsewhere to do the find themselves would AR cash the results of those queries or just the sql? All the queries are in the load function so it would be simple to convert that. – kwbock Sep 22 '11 at 23:17
0

Best not to use class variables - they have very odd behavior. See http://www.oreillynet.com/ruby/blog/2007/01/nubygems_dont_use_class_variab_1.html

In every case you can use civars (class instance variables):

module MyProducts
  class << self
    @products = nil
  end
end
Eric G
  • 1,282
  • 8
  • 18