未在Rails初始化程序中设置Gem的配置
问题描述:
我正在制作一颗红宝石,我们称它为Radin。它用于Rails项目。有一个安装过程通过运行rails generate radin:install
创建config/initializers/radin.rb
。未在Rails初始化程序中设置Gem的配置
配置/初始化/ radin.rb(Rails项目)
Radin.configure do |config|
# Set this options to what makes sense for you
config.option = 'test'
end
发电机按预期工作(如上所见)。在我的宝石中,我遵循MyGem.configure Block和Config and Generators in Gems两个链接。
我有一个可执行文件来检查配置是否已设置。
/EXE /雷丁
#!/usr/bin/env ruby
require 'radin'
output = {}
output["option"] = Radin::Documentor.test_configuration
puts "Output: #{output}"
我的文件处理器类只输出我一个配置选项
/lib/radin/documentor.rb
module Radin
class Documentor
def self.test_configuration
Radin.configuration.option
end
end
end
最后我有我的Radin
模块和Configuration
类
/lib/radin.rb
require "radin/version"
require 'json'
module Radin
autoload :Documentor, 'radin/documentor'
class << self
attr_accessor :configuration
end
def self.configure
self.configuration ||= Configuration.new
yield(configuration)
end
class Configuration
attr_accessor :option
def initialize
@option = 'default_option'
end
end
end
当我运行一个测试Rails应用程序目录中我得到一个错误$ radin
,尽管有在config/initializers/radin.rb
设置的配置选项。
... /雷丁/ lib中/雷丁/ documentor.rb:8:
test_configuration': undefined method
选项”对零:NilClass(NoMethodError)
试图&失败 我试着set将模块更改为始终具有默认设置,但尽管在初始化程序中更改了配置,该选项也不会从“default_option”更改。
module Radin
class << self
attr_accessor :configuration
end
def self.configuration
@configuration ||= Configuration.new
end
def self.configure
yield(configuration)
end
...
答
在我的可执行文件radin
我说:
begin
load File.join(Dir.pwd, 'config', 'initializers', 'radin.rb')
rescue LoadError
puts "Please run `rails generate radin:install` before continuing "
end
,一切似乎现在能够正常工作。