Ruby 类变量和访问分配

发布于 2024-12-06 05:08:54 字数 567 浏览 3 评论 0原文

我有一个具有多个类变量的模块。我正在寻找一个类级别的 getter 实现,当类尝试访问它时,它只会实例化 @@ 变量,如下所示

    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

我正在寻找它是透明的,这样我就不必修改整个模块。大约有 10 个具有类似功能的类级别变量,所有 ActiveRecord .find 调用的结果

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

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

滴情不沾 2024-12-13 05:08:54

只需使用 ||= 运算符即可。仅当正确部分为 nilfalse 时,它才会计算正确的表达式。

def foo
  @@any ||= some_value
end

第一次调用该方法时,它将使用 some_value< 的结果初始化变量/code>,以下调用将返回 @@any 值,无需重新计算 some_value

更新

这是一个小脚本,向您展示如何做到这一点。如果执行该命令,您将看到方法 complex_function 被调用一次,因为两个 print 语句都返回 1。但是从您的评论中我看到您的 Product 是一个活动的记录,所以不要使用这种方法来满足您的要求,它会非常低效(阅读我答案的最后部分)

#!/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

更新结束

但是您保存Product.all<的方法/code> 效率很低:

  • 首先它会获取所有数据库中的产品,当您有很多产品时,可能会消耗大量内存
  • 其次,当您有很多产品时,您的迭代代码将比数据库慢得多

将整个方法替换为Product.find(id) 调用。

如果您的 Product 模型未存储在数据库中(可能是 ActiveResource),请忽略我之前的评论。

您还可以查看 mattr_accessor 和这个问题 mattr_accessor 和ActiveSupport 中的 cattr_accessor?

最后还要看看 这篇文章解释了上述称为记忆化的技术

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

孤星 2024-12-13 05:08:54

最好不要使用类变量 - 它们的行为非常奇怪。看
http://www.oreillynet.com/ruby/blog/2007/01 /nubygems_dont_use_class_variab_1.html

在任何情况下,您都可以使用 civars(类实例变量):

module MyProducts
  class << self
    @products = nil
  end
end

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
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文