简体   繁体   中英

Rails and modules

I want to create a module for query objects. I created a file:

app/queries/invoices/edit.rb

with this class:

module Queries
  module Invoices
    class Edit
    end
  end
end

However, I can't initialize it:

2.3.3 :001 > Queries::Invoices::Edit.new
NameError: uninitialized constant Queries

When I omit the Queries module, everything works:

module Invoices
  class Edit
  end
end


2.3.3 :005 > Invoices::Edit.new
=> #<Invoices::Edit:0x007fc729e15558>

Why is that?

The first level under app isn't considered part of the namespace. It's why you don't say, for instance:

module Models
  class Foo < ActiveRecord::Base
  end
end 

for a model like app/models/foo.rb .

If you want Queries in your namespace, you could do something like:

app/queries/queries/invoices/edit

But, that looks icky to me. I think I'd do something more like:

app/queries/invoice_queries/edit

and then:

module InvoiceQueries
  class Edit
  end
end

@jvillian's answer is correct. However, I don't like both choices :)

What I do in my projects is put all those custom object types into app/lib

app/lib/queries/invoices/edit.rb
app/lib/services/invoices/sync.rb

This way lib serves as that padding, which pushes queries to be part of namespace. Also, all your "non-standard" code is nicely contained in one directory.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM