繁体   English   中英

Rails 应用程序的 Ruby gem:如何在不需要 Rails 的情况下获取“Rails.env”方法?

[英]Ruby gem for Rails app: how to get `Rails.env` method without requiring Rails?

我有 RoR 经验,但我正在研究我的第一个宝石。

gem 专门用于 Rails 应用程序,我想在某些情况下依赖Rails.env

我知道在.gemspec中要求 Rails 是一个坏主意(至少是不好的做法),因为 Rails 很大并且有很多自己的依赖项。

但是Rails.env并不完全是我可以加入的扩展。

Rails.env功能来自railties本身依赖于active_supportaction_dispatch和一堆其他的东西:

require "rails/ruby_version_check"

require "pathname"

require "active_support"
require "active_support/core_ext/kernel/reporting"
require "active_support/core_ext/module/delegation"
require "active_support/core_ext/array/extract_options"
require "active_support/core_ext/object/blank"

require "rails/application"
require "rails/version"

require "active_support/railtie"
require "action_dispatch/railtie"

module Rails
  extend ActiveSupport::Autoload
  extend ActiveSupport::Benchmarkable

  autoload :Info
  autoload :InfoController
  autoload :MailersController
  autoload :WelcomeController

  class << self
    ...

    # Returns the current Rails environment.
    #
    #   Rails.env # => "development"
    #   Rails.env.development? # => true
    #   Rails.env.production? # => false
    def env
      @_env ||= ActiveSupport::EnvironmentInquirer.new(ENV["RAILS_ENV"].presence || ENV["RACK_ENV"].presence || "development")
    end

ActiveSupport::EnvironmentInquirer只是让我能够执行Rails.env.production? 我真的不在乎。

我也可以通过检查ENV["RAILS_ENV"]ENV["RACK_ENV"]来模仿这种行为,但是如果Rails.env发生了变化,这不会改变ENV变量:

3.0.2 :001 > Rails.env
 => "development" 
3.0.2 :005 > ENV["RAILS_ENV"]
 => "development" 
3.0.2 :006 > ENV["RACK_ENV"]
 => "development" 
3.0.2 :007 > Rails.env = 'test'
 => "test" 
3.0.2 :008 > Rails.env
 => "test" 
3.0.2 :009 > ENV["RAILS_ENV"]
 => "development" 
3.0.2 :010 > ENV["RACK_ENV"]
 => "development" 

或者我可以将类实例化为 PORO,但这似乎也是不好的做法:

module Rails
  def self.env
    @_env ||=
      ENV['RAILS_ENV'] ||
      ENV['RACK_ENV'] ||
      'development'
  end
end

现在我只是在Rails抛出名称错误时进行救援:

@environment =
  begin
    Rails.env
  rescue NameError
    'development'
  end

有没有标准的方法来完成这个,或者我的rescue是最好的方法?

你可以使用defined? 检查是否定义了顶级常量Rails

def rails_env
  ::Rails.env if defined?(::Rails)
end

如果您想更加安全:

def rails_env
  ::Rails.env if defined?(::Rails) && ::Rails.respond_to?(:env)
end

强制使用纯字符串:(而不是ActiveSupport::EnvironmentInquirer实例)

def rails_env
  ::Rails.env.to_s if defined?(::Rails) && ::Rails.respond_to?(:env)
end

有了上面你可以写:

@environment = rails_env || 'development'

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM