Sutto / rocket_pants

API building tools on top of ActionController. Also, an awesome name.
MIT License
981 stars 130 forks source link

Example of Namespace with Controllers with Rocket Pants #68

Closed sricc closed 11 years ago

sricc commented 11 years ago

I'm new to Rails and Ruby and was wondering if you could give an example for this statement:

"And in the case of multiple versions, I strongly encourage namespaces the controllers inside modules."

Your original example:

class UsersController < RocketPants::Base
  version 1 # A single version
  # or...
  version 2..3 # 2-3 support this controller
end

Then in routes:

api :versions => 1..3 do
  get 'x', :to => 'test#item'
end

How would these change? What would the folder structure look like??

- app
  - controllers
     - api
       - v1

Thanks.

Sutto commented 11 years ago

Hey there Steve,

So, first - Rails loads using a structure - so your file system layout is correct - Using the users example,

it'd be app/controllers/api/v1/users_controller.rb - Rails is smart enough to expect the controller Api::V1::UsersController in that file - so you declare it as such:

class Api::V1::UsersController < RocketPants::Base
  version 1

  def index
    expose User.all # Not what we'd actually do...
  end

end

Note that I'd probably also introduce Api::V1::BaseController, and inherit from that - that way any shared logic (e.g. authentication) can be put in there - I can do an example of that if you'd like?

Finally, in the routes - the easiest way would be in the api declaration:

api versions: 1, module: "api/v1" do
  resources :users, only: [:index]  
end

Which will set up /1/users to hit the index action of Api::V1::UsersController - the module parameter comes from the rails built in routing stuff: http://api.rubyonrails.org/classes/ActionDispatch/Routing/Mapper/Scoping.html#method-i-scope

sricc commented 11 years ago

Hey Darcy,

Thank you very much for the explanation and the examples, it was very helpful. This is probably natural to the experienced Rails developer, but it might be nice to provide this explanation in the README near the statement.

"And in the case of multiple versions, I strongly encourage namespaces the controllers inside modules."

Now, everything is working!

Thanks again for getting back to me. I really appreciate it!

CTres commented 11 years ago

Great overview - thanks so much!

Sutto commented 11 years ago

Sweet, cheers guys. I'll add it to the README