保存动态Ruby类

Jos*_*ore 5 ruby

我有一个好奇的问题.如果我有一个ruby类然后我在执行期间动态添加类方法,类变量等,那么我还是保存更改的类定义,以便下次启动我的应用程序时我可以再次使用它吗?

toh*_*lio 1

简单地编组对象(正如其他人所说)是行不通的。让我们看一个例子。考虑这个类:

class Extras
  attr_accessor :contents
  def test
    puts "This instance of Extras is OK. Contents is: " + @contents.to_s
  end

  def add_method( name )
    self.class.send :define_method, name.to_sym do
      puts "Called " + name.to_s
    end
  end
end
Run Code Online (Sandbox Code Playgroud)

现在让我们编写一个程序来创建一个实例,向其添加一个方法并将其保存到磁盘:

require 'extras'

fresh = Extras.new
fresh.contents = 314
fresh.test # outputs "This instance of Extras is OK. Contents is: 314"
fresh.add_method( :foo )
fresh.foo # outputs "Called foo"

serial = Marshal.dump( fresh )
file = File.new "dumpedExample", 'w'
file.write serial
Run Code Online (Sandbox Code Playgroud)

所以我们可以调用普通方法“test”和动态方法“foo”。让我们看看如果我们编写一个程序来加载保存到磁盘的 Example 实例会发生什么:

require 'extras'

file = File.new 'dumpedExample', 'r'
serial = file.read

reheated = Marshal.load( serial )
reheated.test # outputs "This instance of Extras is OK. Contents is 314"
reheated.foo # throws a NoMethodError exception 
Run Code Online (Sandbox Code Playgroud)

所以我们可以看到,虽然实例(包括成员变量的值)被保存,但动态方法却没有保存。

从设计的角度来看,最好将所有添加的代码放入模块中,并在下次运行程序时将其再次加载到类中。我们需要一个很好的例子来说明您可能想要如何使用它,但要真正了解这一点。

如果您需要额外的信息来重新创建方法,请让模块将它们保存为成员变量。在模块中实现included,并在将其包含到类中时让它查找这些成员变量。