Ruby namespacing

后端 未结 3 928
温柔的废话
温柔的废话 2020-12-10 05:32

I\'m pretty new to ruby, coming from a php background, but something is not clicking with me.

So, let\'s say I have a Ruby on Rails application and I am versioning m

3条回答
  •  半阙折子戏
    2020-12-10 05:49

    You should check the guide to understand the routing: http://guides.rubyonrails.org/routing.html#controller-namespaces-and-routing

    I think this question is very similar to:

    Rails Controller Namespace

    And as shortage:

    Rails will detect the namespace automagically by the folder. So you don't need to append it to the name:

    This blog post explains it so well:

    http://blog.makandra.com/2014/12/organizing-large-rails-projects-with-namespaces/

    Let's say we have an Invoice class and each invoice can have multiple invoice items:

    class Invoice < ActiveRecord::Base
      has_many :items
    end
    
    class Item < ActiveRecord::Base
      belongs_to :invoice
    end
    

    Clearly Invoice is a composition of Items and an Item cannot live without a containing Invoice. Other classes will probably interact with Invoice and not with Item. So let's get Item out of the way by nesting it into the Invoice namespace. This involves renaming the class to Invoice::Item and moving the source file to app/models/invoice/item.rb:

     class Invoice::Item < ActiveRecord::Base
       belongs_to :invoice
     end
    

    Same is applied to controllers and views.

提交回复
热议问题