Sky
Sky

Reputation: 4853

Rails 3 trouble with namespaces & custom classes (uninitialized constant)

I have a file in my Rails 3.2.11 project called app/queries/visible_discussions.rb which looks like the following:

class VisibleDiscussions
  ...
end

I'd like to namespace the query so that I can call it using something like Queries::VisibleDiscussions so I tried to do the following:

module Queries
  class VisibleDiscussions
    ...
  end
end

However, I'm getting a uninitialized constant Queries (NameError) when I try to call Queries::VisibleDiscussions from the rails console.

Any ideas?

Upvotes: 2

Views: 2591

Answers (2)

house9
house9

Reputation: 20614

if you add lib to your autoload_paths then it will respect the namespacing under lib - lib/query/visible_discussions.rb

or create a new dir under app - say src and then nest your code there - app/src/query/visible_discussions.rb

i would use the 3rd style in your post for either of these, i.e.

module Query
  class VisibleDiscussions
    ...
  end
end

both of these solutions are annoying to me, there might be a way to tell rails to namespace directories under app, but i have no clue how it would be done

Upvotes: 3

charlysisto
charlysisto

Reputation: 3700

Rails needs to know what directories to load (a part from the defaults). Try:

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

Upvotes: 0

Related Questions