59

I am trying to reference an association extension but it errors with:

NameError (uninitialized constant User::ListerExtension):
  app/models/user.rb:2:in `<class:User>'

Here is my implementation:

app/models/user.rb

class User < ActiveRecord::Base
  include ListerExtension

  has_and_belongs_to_many :roles, :uniq => true, :extend => Lister

lib/lister.rb

module ListerExtension
  def lister
    self.map(&:to_s).join(', ')
  end
end

I am using Rails v3.1.3.

Andrew Marshall
  • 95,083
  • 20
  • 220
  • 214
Coderama
  • 11,050
  • 12
  • 44
  • 58
  • 6
    possible duplicate of [Best way to load module/class from lib folder in Rails 3?](http://stackoverflow.com/questions/3356742/best-way-to-load-module-class-from-lib-folder-in-rails-3) – Andrew Marshall Sep 06 '12 at 14:39

2 Answers2

100

Andrew Marshall has an excellent point about the auto-load setup (see the question he links for more on that), but also: Because you named your class ListerExtension, Rails will be looking for a file named lister_extension.rb - not lister.rb. It's smart, but it's not that smart.

starball
  • 20,030
  • 7
  • 43
  • 238
Xavier Holt
  • 14,471
  • 4
  • 43
  • 56
  • 3
    And [here](https://groups.google.com/forum/?hl=en&fromgroups=#!topic/rubyonrails-talk/Ziq_0d-bJhI)'s a link with a few more useful details. – Xavier Holt Sep 06 '12 at 19:05
  • 5
    or create a initializer file ( in config/initializer) that requires your file, something like: require 'listener.rb' – eveevans Feb 08 '13 at 18:01
  • This totally bit me today. I updated the file name and all was right with my code again. :) – Abel Feb 20 '13 at 22:43
  • For anyone else, I noticed something like include ProfileHelper worked when rails server was running but not once restarted. I needed Api::ProfileHelper to make the server happy when starting. – Eddie Aug 07 '15 at 13:15
0

complementing the answer above

My problem was solved when I used require 'module-relative-path' in the file I want to include the module

require './lib/lister.rb' #check if this is the right relative path

 class User < ActiveRecord::Base
  include ListerExtension

  has_and_belongs_to_many :roles, :uniq => true, :extend => Lister