【问题标题】:Ruby Motion: Removing a Ruby Class Completely from Object SpaceRuby Motion:从对象空间中完全移除一个 Ruby 类
【发布时间】:2012-11-08 17:35:14
【问题描述】:

我在测试类重新定义时遇到了难题,只是不知道如何处理它。这是我正在测试的场景(这不是核心数据):

  • 应用程序使用版本 1 中的模型运行
  • 热切的程序员通过添加/删除/重新定义列来修改模型
  • 应用程序使用版本 2 中的模型运行

我遇到问题的地方是模拟从内存中实际删除应用程序并从头开始重建它。这很重要,因为在包含 MotionModel::Model 模块时会设置许多特定于模型的东西,并且只会发生一次:当模块包含在类中时。以下是我认为可能有效的方法:

  it "column removal" do
      class Removeable
        include MotionModel::Model
        columns       :name => :string, :desc => :string
      end


      @foo = Removeable.create(:name=> 'Bob', :desc => 'who cares anyway?')


      Removeable.serialize_to_file('test.dat')

      @foo.should.respond_to :desc

      Object.send(:remove_const, :Removeable)  # Should remove all traces of Removeable
      class Removeable
        include MotionModel::model             # Should include this again instead
        columns       :name => :string,        # of just reopening the old Removeable
                      :address => :string      # class
      end


      Removeable.deserialize_from_file # Deserialize old data into new model


      Removeable.length.should == 1
      @bar = Removeable.first
      @bar.should.respond_to :name
      @bar.should.respond_to :address      
      @bar.should.not.respond_to :desc


      @bar.name.should == 'Bob'
      @bar.address.should == nil
    end
  end

不幸的是,Object.send(:remove_const, :Removeable) 并没有像我希望的那样做,Ruby 只是认为它可以重新打开 Removeable 而不运行 MotionModel::Model 模块的 self.included() 方法。

关于如何在规范示例的上下文中从头开始模拟创建此类的任何想法?

【问题讨论】:

  • 可能是一个愚蠢的建议,但您是否尝试使用字符串而不是符号? “可移动”?
  • 我在对 MotionModel 的提交中使用 Object.send(:remove_const, :Foo) if defined?(Foo) 很好,也许这不再是问题?也许 RubyMotion 的 1.35 版本的缓存修复解决了这个问题。

标签: ruby testing rubymotion


【解决方案1】:

我会尝试使用匿名类(您必须告诉 MotionModel 表名)。

虚构的例子:

model_before_update = Class.new do
  # This tells MotionModel the name of the class (don't know if that actually exists)
  table_name "SomeTable"
  include MotionModel::Model
  columns       :name => :string, :desc => :string
end

您根本没有删除该类,您只需定义另一个具有相同表名的(匿名)类。

model_after_update = Class.new do
  table_name "SomeTable"
  include MotionModel::model
  columns       :name => :string,
                :address => :string
end

想想看,如果有像上面这样的 table_name 设置器,你甚至不需要使用匿名类,以防 RubyMotion 不起作用。

【讨论】:

  • 这是个好主意。我认为它会破坏一些代码并且不如我计划的那么直观,但是 table_name 设置器总是一个好主意。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2011-03-07
  • 2016-07-03
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-04-16
  • 1970-01-01
相关资源
最近更新 更多