Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 219
user502052 Avatar asked May 02 '11 01:05

user502052


People also ask

What is the difference between namespace and class?

The namespace and classes are two different concepts. Classes are datatypes. Classes are basically extended version of structures. Classes can contain data members and functions as members, but namespaces can contain variables and functions by grouping them into one.

What is namespace in programming language?

A namespace is a declarative region that provides a scope to the identifiers (the names of types, functions, variables, etc) inside it. Namespaces are used to organize code into logical groups and to prevent name collisions that can occur especially when your code base includes multiple libraries.

What is Namespacing in Ruby?

A namespace is a container for multiple items which includes classes, constants, other modules, and more. It is ensured in a namespace that all the objects have unique names for easy identification. Generally, they are structured in a hierarchical format so, that names can be reused.


1 Answers

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.

  • Namespaced models and controllers

Some alternatives to using namespaces in models

  • A simple alternative to namespaced models

Hope this helps.

like image 113
thekindofme Avatar answered Oct 04 '22 05:10

thekindofme