【问题标题】:How to call a method to load class variable in Ruby?如何在 Ruby 中调用加载类变量的方法?
【发布时间】:2012-04-16 17:57:31
【问题描述】:

数据被加载一次,因为加载需要一段时间,不会改变,并且是共享的。这是一个静态类:我没有使用任何实例。

class Foo
  @@ data = self.load_data

  def self.load_data
    .
    . 
    .
  end

  def self.calculate
    .
    .
  end
end

这会引发错误NoMethodError: undefined method 'load_data' for Foo:Class,因为 load_data 出现在分配之后。

我不认为初始化会起作用,因为我没有使用f = Foo.new。我将其用作Foo.calculate

调用前需要声明load_data吗?还是有更好的方法?

【问题讨论】:

    标签: ruby-on-rails ruby class static-methods static-variables


    【解决方案1】:

    是的 Foo.load_data 在你调用它的时候还不存在。

    更好的模式可能是拥有一个自动记忆的@@data 访问器。

    class Foo
      def self.data
        @@data ||= load_data
      end
      def data; self.class.data; end # if you need it in instances too
    
      def self.load_data
        ...
      end
    
      def self.calculate
        data.each {} # or whatever would have used @@data
      end
    end
    

    【讨论】:

      【解决方案2】:

      通过类级函数调用加载数据。

      class Foo
        def self.load_data
          .
          . 
          .
          @data = value
        end
      
        def self.calculate
         #use @data in this function.
         .
         .
        end
      end
      
      #first load data
      Foo.load_data
      
      #then process data
      Foo.calculate
      

      【讨论】:

      • Foo.calculate 是通过一个 cron 作业运行的,所以没有好时机调用 load_data。在这种情况下,最好以某种方式自动加载...
      • 然后从calculate方法调用load_data。
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2019-05-19
      • 2012-03-07
      • 2011-07-24
      • 2011-09-02
      • 2023-03-19
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多