Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
531 views
in Technique[技术] by (71.8m points)

ruby on rails - Handling namespace models (classes) in namespace

I am using Ruby on Rails 3 and I would like to handle models (classes) namespaces within namespaces. That is, if I have a namespace named NS1 and a "sub-namespace" of that namespace named NS2, I would like to handle models (classes) in NS2.

If I run a scaffold

rails generate scaffold ns1/ns2/Article id:integer title:string

it will generate following model files:

models/ns1/ns2/article.rb file
models/ns1/articles.rb

The models/ns1/articles.rb contains:

module Ns1::Articles
  def self.table_name_prefix
    'ns1_articles_'
  end
end

What is the models/ns1/articles.rb file? How and why can I use that? Have you advices about using that?

And, in general, what is "the best" way to handle "composed" classes in namespaces using Ruby on Rails?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

The

models/ns1/articles.rb

is basically setting the table name prefix for all the model classes under that namespace. Thats its use. It's more DRY'ish to do in there (in a single file), rather than setting the prefix in every model class under that namespace.

I am not a big fan of using namespaces in my models. However you could refer to the following articles to gain a better understanding about using namespaces in modules.

Some alternatives to using namespaces in models

Hope this helps.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...