在方法中收集初始化的ActiveModel实例?

问题描述 投票:0回答:1

如何在方法执行期间获取所有实例化的ActiveModel实例?

class Foo
  def some_method
    Post.new title: 'First title'
    Post.new title: 'Second title'
  end
end

module Launcher
  def self.launch!
    fooser = Foo.new
    new_posts = Post.watch do
      fooser.some_method()
    end

    # new_posts => #<Enumerator [#2 initialized Posts#]>
    # Some logic for saving all these initialized objects at once
  end
end

Launcher.launch!
ruby-on-rails ruby
1个回答
1
投票

如果您可以修改源,最简单的方法就是从您的方法中返回一个数组。

def some_method
  [
    Post.new title: 'First title',
    Post.new title: 'Second title',
  ]
end

但是,我认为您的解决方案不是那么简单,您实际上想收集在块执行期间启动的所有模型。

最简单的方法是为此使用after_initialize并将记录存储到例如类变量中。

def self.watch
  @records = []
  @watching = true
  yield
ensure
  @watching = false
  @records
end

def self.record_initialized(record)
  @records << record if @watching
end

after_initialize { |record| record.class.record_initialized(record) }

如果您想使用一个查询插入它们,请查看.insert_all

© www.soinside.com 2019 - 2024. All rights reserved.