Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Production uninitialized constant custom class stored in lib (heroku)

I have a custom class stored in /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

I'm attempting to use this this class in an Active Admin resource and get the following error when in production (Heroku):

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

It's worth noting I have this line in my application.rb and that this functionality works locally in development:

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

If I try include BufferApp or require 'BufferApp' that line itself causes an error. Am I having a namespace issue? Does this need to be a module? Or is it a simple configuration oversight?

like image 748
Jayson Lane Avatar asked Jun 20 '13 13:06

Jayson Lane


3 Answers

I had exactly the same problem with Rails 5 alpha. To solve it, I had to manually require the file:

require 'buffer_app'

and not: (require 'BufferApp')

Even if Michal Szyndel's answer makes great sense to me, after manually requiring the file, prefixing :: to the constant was non influential in my case.

Anyway I am not satisfied with the manual requiring solution because I need to add code which is environment specific. Why don't I need to require the files manually in development?

like image 52
masciugo Avatar answered Oct 05 '22 11:10

masciugo


Change this

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

to this

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

eager_load_paths will get eagerly loaded in production and on-demand in development. Doing it this way, you don't need to require every file explicitly.

See more info on this answer.

like image 31
Jonathan Tran Avatar answered Oct 05 '22 12:10

Jonathan Tran


Error line says it all, you should reference class as ::BufferApp

like image 24
Mike Szyndel Avatar answered Oct 05 '22 12:10

Mike Szyndel