动态生成Rails安全权标方法

因为Rails使用安全权标来加密会话,所以生成Rails项目后,需要修改默认的secret_token文件。

将config/initializers/secret_token.rb里自动生成的字符串改为:

require 'securerandom'

def secure_token
  token_file = Rails.root.join('.secret')
  if File.exist?(token_file)
    # Use the existing token.
    File.read(token_file).chomp
  else
    # Generate a new token and store it in token_file.
    token = SecureRandom.hex(64)
    File.write(token_file, token)
    token
  end
end

SampleApp::Application.config.secret_key_base = secure_token

同时需要在.gitignore 文件里加入“ .secret ”。

原文地址:https://www.cnblogs.com/leaf526/p/3603496.html