Backo
Backo

Reputation: 18871

Retrieve the controller name from a class name following RoR conventions

I am using Ruby on Rails 3.0.9 and I would like to build a controller name from a class name as well as possible following RoR naming conventions. For example, if I have the Articles::Comment class I would like to retrieve the articles/comments string.

Maybe it exists a RoR method created by developers to handle internally these conventions, but I don't know that.

How can I retrieve the controller name as in the example above?

Upvotes: 1

Views: 242

Answers (1)

Maurício Linhares
Maurício Linhares

Reputation: 40313

You're looking for the underscore method. More info here.

"Articles::Comment".underscore

Or, if you've got the controller class itself, it would be like this:

Articles::Comment.name.underscore

EDIT

As of routes, they are built one piece at a time, even when you namespace them. When you do something like this:

map.resources :articles do |articles|
  articles.resources :comments
end

What rails is going to do is, first:

"articles". classify # which yields "Article" then rails is going to append "Controller" to it

Then it's going to get "comments" and do the same, but this one is going to be routed under "/articles". Rails does not namespace internal resources, so, the controller has to be CommentsController, not Articles::CommentsController.

Only then you clearly namespace something, Rails is going to namespace your classes:

map.namespace :admin do |admin|
  admin.resources :articles # will require controller "Admin::ArticlesController"
end

I hope it's clearer now.

Upvotes: 3

Related Questions