【问题标题】:Modifying the Rails Object for the seed process修改种子进程的 Rails 对象
【发布时间】:2017-12-28 19:32:31
【问题描述】:

是否可以修改 Rails obj?

我只想简单修改一下,然后改回来。

我的推理: 我正在尝试处理我的种子文件并使其更加健壮。

在我的模型中有一个查看当前控制器和当前用户的进程,它会在会话期间跟踪该用户。

在我的种子测试期间它会抛出一个错误,因为没有基于控制器的用户会话。

我想做的是添加 Rails.seed = true

在我的种子开始时,它会到达模型,在模型中,我会在设置跟踪的块周围为这个属性包装一个控制流(if 语句)。

然后我会删除 Rails.seed = true 在种子文件的末尾。

【问题讨论】:

  • 如果您希望在运行测试和常规运行时之间有不同的行为,为什么不使用环境变量呢? Rails.env['seeding']

标签: ruby-on-rails ruby environment-variables seed


【解决方案1】:

不用直接放在Rails对象上,可以使用custom configuration

config/initializers/custom_config.rb(名称不重要,只是在初始化程序中)

Rails.configuration.seeding = false

db/seeds.rb

Rails.configuration.seeding = true

User.create

app/models/user.rb

class User < ApplicationRecord
  # just as an example
  after_initialize do
    if Rails.configuration.seeding
      puts "Seeding DB"
    else
      puts "Normal"
    end
  end
end

输出

$ bin/rake db:seed
# Running via Spring preloader in process 19017
# Seeding DB
$ bin/rails c
User.create
# Normal
# => #<User ...>

【讨论】:

    【解决方案2】:

    我不一定建议修改 Rails 类,但要实现这一点,您可以执行以下操作:

    class Rails
      attr_accessor :seeding
    
      def seeding=(bool)
        @seeding = bool
      end
    
      def seeding?
        @seeding ||= false
      end
    end
    

    然后您可以使用Rails.seeding = true 设置它并使用Rails.seeding? 访问它。如果未设置,它也将默认为 false。

    另一种解决方案可能是将正在爆炸的部分包装在 being rescue 块中以捕获错误。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-09-18
      • 2013-02-18
      • 2014-10-14
      • 1970-01-01
      • 2012-05-30
      • 1970-01-01
      相关资源
      最近更新 更多