56

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
  • 92,562
  • 20
  • 215
  • 211
Coderama
  • 10,456
  • 12
  • 40
  • 57
  • 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

1 Answers1

96

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.

Hope that helps!

Romain Piel
  • 10,807
  • 15
  • 69
  • 105
Xavier Holt
  • 14,301
  • 3
  • 41
  • 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