2017-07-22 133 views
0

是否可以修改Rails obj?修改種子進程的Rails對象

我只想修改它並簡單地修改它。

我的推理: 我想在我的種子文件上工作,並使其更健壯一點。

在我的模型中有一個查看當前控制器和當前用戶的進程,它在那裏會話期間跟蹤此用戶。

它在我的種子測試期間拋出一個錯誤,因爲沒有基於控制器的用戶會話。

我想要做的是在我的種子開始添加 Rails.seed = true

,它將獲得到模型和模型中我會換一個控制流(if語句)周圍的這個屬性阻止設置跟蹤。

然後我會刪除種子文件末尾的 Rails.seed = true

+0

如果你想在運行測試,並定期運行時之間不同的行爲,爲什麼不使用環境變量? 'Rails.env [ '播種']' – Andrei

回答

0

我不一定會建議修改的Rails類,但實現你可以這樣做:

class Rails 
    attr_accessor :seeding 

    def seeding=(bool) 
    @seeding = bool 
    end 

    def seeding? 
    @seeding ||= false 
    end 
end 

那麼你可以使用Rails.seeding = true進行設置,並Rails.seeding?訪問它。如果未設置,它將默認爲false。

另一種解決方案可能被包裹被吹在beingrescue塊捕獲錯誤的部分。

2

而不是把它直接在Rails對象,你可以使用custom configuration

配置/初始化/ custom_config.rb(名字不重要,只是在初始化)

Rails.configuration.seeding = false 

DB/seeds.rb

Rails.configuration.seeding = true 

User.create 

應用程序/模型/ 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 ...>