Ruby on rails 修改种子进程的Rails对象

Ruby on rails 修改种子进程的Rails对象,ruby-on-rails,ruby,environment-variables,seed,Ruby On Rails,Ruby,Environment Variables,Seed,是否可以修改Rails obj 我只想简单地修改一下,然后再修改回来 我的理由是: 我正在努力处理我的seeds文件,使它更加健壮 在我的模型中,有一个进程查看当前控制器和当前用户,它在该会话期间跟踪该用户 但在种子测试期间它会抛出一个错误,因为没有基于控制器的用户会话 我想做的是补充一下 Rails.seed=true 在我的seed开始时,它将到达模型,在模型中,我将围绕设置跟踪的块为该属性包装一个控制流(if语句) 然后我会移除 Rails.seed=true 在种子文件的末尾。我

是否可以修改Rails obj

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

我的理由是: 我正在努力处理我的seeds文件,使它更加健壮

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

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

我想做的是补充一下

Rails.seed=true

在我的seed开始时,它将到达模型,在模型中,我将围绕设置跟踪的块为该属性包装一个控制流(if语句)

然后我会移除

Rails.seed=true

在种子文件的末尾。

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

class Rails
  attr_accessor :seeding

  def seeding=(bool)
    @seeding = bool
  end

  def seeding?
    @seeding ||= false
  end
end
然后可以使用
Rails.seaking=true
对其进行设置,并使用
Rails.seaking?
访问它。如果未设置,它也将默认为false


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

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

class Rails
  attr_accessor :seeding

  def seeding=(bool)
    @seeding = bool
  end

  def seeding?
    @seeding ||= false
  end
end
然后可以使用
Rails.seaking=true
对其进行设置,并使用
Rails.seaking?
访问它。如果未设置,它也将默认为false


另一种解决方案可能是将爆炸的零件包装在一个
rescue
块中以捕获错误。

您可以使用

config/initializers/custom_config.rb(名称不重要,仅在初始值设定项中)

db/seeds.rb

Rails.configuration.seeding = true

User.create
class User < ApplicationRecord
  # just as an example
  after_initialize do
    if Rails.configuration.seeding
      puts "Seeding DB"
    else
      puts "Normal"
    end
  end
end
app/models/user.rb

Rails.configuration.seeding = true

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

$ bin/rake db:seed
# Running via Spring preloader in process 19017
# Seeding DB
$ bin/rails c
User.create
# Normal
# => #<User ...>
$bin/rake数据库:种子
#通过过程19017中的弹簧预紧器运行
#种子数据库
$bin/c
User.create
#正常的
# => #

您可以使用

config/initializers/custom_config.rb(名称不重要,仅在初始值设定项中)

db/seeds.rb

Rails.configuration.seeding = true

User.create
class User < ApplicationRecord
  # just as an example
  after_initialize do
    if Rails.configuration.seeding
      puts "Seeding DB"
    else
      puts "Normal"
    end
  end
end
app/models/user.rb

Rails.configuration.seeding = true

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

$ bin/rake db:seed
# Running via Spring preloader in process 19017
# Seeding DB
$ bin/rails c
User.create
# Normal
# => #<User ...>
$bin/rake数据库:种子
#通过过程19017中的弹簧预紧器运行
#种子数据库
$bin/c
User.create
#正常的
# => #

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