存储在lib(heroku)中的生成未初始化的常量自定义类

时间:2013-06-20 13:41:39

标签: ruby-on-rails class heroku namespaces

我有一个存储在/ lib中的自定义类(/lib/buffer_app.rb):

require 'HTTParty'

class BufferApp
  include HTTParty
  base_uri 'https://api.bufferapp.com/1'

  def initialize(token, id)
    @token = token
    @id = id
  end

  def create(text)
    message_hash = {"text" => text, "profile_ids[]" => @id, "access_token" => @token}

    response = BufferApp.post('/updates/create.json', :body => {"text" => text, "profile_ids[]" => @id, "access_token" => @token})
  end
end

我正在尝试在Active Admin资源中使用此类,并在生产(Heroku)时出现以下错误:

NameError (uninitialized constant Admin::EventsController::BufferApp):

值得注意的是,我的application.rb中有这一行,并且此功能在开发中本地工作:

config.autoload_paths += %W(#{Rails.root}/lib)

如果我尝试include BufferApprequire 'BufferApp'该行本身会导致错误。我有命名空间问题吗?这需要是一个模块吗?或者这是一个简单的配置疏忽?

3 个答案:

答案 0 :(得分:8)

我对Rails 5 alpha有完全相同的问题。要解决它,我不得不手动要求文件:

require 'buffer_app'

而不是:(require 'BufferApp'

即使Michal Szyndel的回答对我来说很有意义,但在手动要求文件之后,::前缀为常量对我的情况没有影响。

无论如何,我对手动需求解决方案不满意,因为我需要添加特定于环境的代码。为什么我不需要在开发中手动要求文件?

答案 1 :(得分:4)

更改此

config.autoload_paths += %W(#{Rails.root}/lib)

到这个

config.eager_load_paths += %W(#{Rails.root}/lib)

eager_load_paths将在生产和开发中按需加载。这样做,您不需要明确要求每个文件。

查看有关this answer的更多信息。

答案 2 :(得分:3)

错误行说明了所有内容,您应该将类​​引用为::BufferApp