繁体   English   中英

依次运行红宝石方法

[英]Run ruby methods one after the other

我创建了一个医生导入程序,但是我想先运行并完成一些方法,例如创建新的办公室等,然后再更新该医生的数据。 它们在run方法上是否同时运行? 还是方法一次运行一次?

红宝石

  def run
    # Create all of our dependencies
    create_hospitals
    create_departments
    create_specialties
    create_offices

    # Map the dependencies to each doctor
    map_hospitals
    map_departments
    map_specialties
    map_offices

    # Save the mapped data, then traverse and create doctors that don't exist
    @record.save
    update_doctors  # Update existing physicians
    create_doctors  # Create new physicians

    # Update the record status
    @record.import_log.empty? ? @record.completed! : @record.failed!
  end

我希望在运行更新方法之前先运行并完成第一个create和map方法。

Ruby将按照调用它们的顺序运行这些方法。 Ruby默认不是异步的。 但是在Rails中很常见,建议使用异步后台作业。 有关如何进行设置的想法,请参阅文档

另外,查看运行方法内部的一长串方法,却不知道它们做什么,我只能推测可能存在一些复杂的业务逻辑。 您可能还想看一下有关Rails中的交互器的文章,这在这种情况下可能是有用的设计模式。 另请参阅以下相关的gem, interactoractiveinteractor

它们将按顺序运行。 您可以生成多个线程并同时启动它们,但是请记住Ruby具有GIL ,因此,只有其中一些函数进行Web调用或其他O / I操作时,它才会对您有利。

如果您决定要这样做,可以使用Concurrent Ruby之类的库来简化它。 https://github.com/ruby-concurrency/concurrent-ruby

如果您在Rails中执行此操作,则Active Record回调将使您能够调用所有这些方法,以便可以在预期函数执行之前或之后执行。 示例如下:

创建一个对象

before_validation
after_validation
before_save
around_save
before_create
around_create
after_create
after_save
after_commit/after_rollback

更新对象

before_validation
after_validation
before_save
around_save
before_update
around_update
after_update
after_save
after_commit/after_rollback

销毁对象

before_destroy
around_destroy
after_destroy
after_commit/after_rollback

请参阅有关HERE的更多详细信息,它将大大有助于使您的代码变干。 您还可以通过将它们定义为方法来覆盖这些回调,以便在需要时将其扩展为您的期望。

Ruby函数按调用顺序运行。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM