user1748485
user1748485

Reputation:

uninitialized constant for module included in model

I've read a bunch of other SO posts on this and it seems the convention is to place the module in lib (lib/my_module.rb) and name it CamelCase (module MyModule) and then include it in the model (include MyModule). I did all this and still get "uninitialized constant Model::MyModule". I was wondering if something changed in Rails 4 or if I have to do something in my config/environment.rb file. Here is my code:

app/models/comment.rb

class Comment < ActiveRecord::Base
    include KarmaExtension # error at this line

    belongs_to :user
    belongs_to :post
    belongs_to :parent, class_name: "Comment"

    ...
end

lib/karma_extension.rb

module KarmaExtension
    def karma_recieved_from?(sender)
        sender ? !karmas.where("sender_id = ?", sender.id).empty? : true
    end
end

and my config/environment.rb just in case (have not touched this file)

# Load the Rails application.
require File.expand_path('../application', __FILE__)

# Initialize the Rails application.
RailsHnClone::Application.initialize!

Upvotes: 3

Views: 1824

Answers (1)

spickermann
spickermann

Reputation: 106882

Add /lib to your load_path:

# in config/application.rb
config.autoload_paths += %W(#{config.root}/lib)

And require your lib:

# in config/initializers/karma_extension.rb
require 'karma_extension'

Found the answer here: http://blog.chrisblunt.com/rails-3-how-to-autoload-and-autorequire-your-custom-library-code/

Upvotes: 2

Related Questions