0
Rails Gems realize RESTfulmodeling patterns@tkawaRubyKaigi 2013, June 1
@tkawaRuby programmer (2000-)*RESTafarian (2005-)inspired by @yoheiRails programmer (2006-)*Sendagaya.rb (2012-)Toru KAWAM...
Sendagaya.rb 『千駄ヶ谷.rb』Every Monday 19:00 - 21:30
Sendagaya.rbOrganized by @ppworks, @fukajun, and meConcept: Looking forward to the weeklymeetup makes our everyday working...
Rails Gems realize RESTfulmodeling patterns@tkawa
Rails Gems realize RESTfulresource modeling patterns@tkawa
Point of Departure
Rails is RESTful
Since RubyKaigi 2006June 11, 2006
# config/routes.rbFoobar::Application.routes.draw doresources :usersend
resources :users
GET /users users#indexPOST /users users#createGET /users/new users#newGET /users/:id/edit users#editGET /users/:id users#s...
GET POST PUT DELETE/users index create - -/users/:id show - update destroyin addition, “new” and “edit” as supplementary r...
resources :usersThat’s it.That makes for really simple design.
REST’s advantage is...
SimpleConsistentTo reap the benefits ofHTTP (“HTTP way”)Generally:
Easy to designEasy to understandOn Rails “resources”particularly:
“resources” makes iteasy to designFor developer him/herself“resources” decides on a resource formAll you have to do is to ...
“resources” makes iteasy to understandFor developer him/herself, co-developer,and external developer (e.g. using API)Sugge...
“resources” makes iteasy to design & understandRails has demonstrated thatthis simplicity goes well“Constraints are libera...
You might think it does notgo well in these cases:
AuthenticationSearchState changesExecution of procedural operationOperation to a list / SortWizard / Confirmation page
AuthenticationSearchState changesExecution of procedural operationOperation to a list / SortWizard / Confirmation pageHow d...
We need another technique.But...
resources :users
GET POST PUT DELETE/users index create - -/users/:id show - update destroyin addition, “new” and “edit” as supplementary r...
GET POST PUT DELETE/users index create - -/users/:id show - update destroyThis is a pattern
“resources” makes iteasy to design & understand
A pattern makes iteasy to design & understand
“resources” is the fundamental patternIf there is a smaller and more concretepattern, we can design well accordinglyWe wan...
コストがかかるかもしれない問題解決を実際に行う前の先行調査として大変役に立つパターンには名前がついていることが重要である。なぜなら、名前がついていることで問題や解決策を記述したり、会話の中で取り上げたりすることができるようになるからであるja....
Using a pattern is similarto Rails way, and...
We have “RubyGems”
Suppose a gem provides theimplementation of a specific patternThen routes.rb will be the description ofthe patterns to be u...
Discover the patternfrom RubyGems
AuthenticationSearchState changesExecution of procedural operationOperation to a list / SortWizard / Confirmation page
Authentication“Sign in” / “Sign out”Those are represented as what?
devise.plataformatec.com.brDeviseby Plataformatec
GET /users/sign_in devise/sessions#newPOST /users/sign_in devise/sessions#createDELETE /users/sign_out devise/sessions#des...
“Sessions” is a resource(that doesn’t involve a model)GET /users/sign_in devise/sessions#newPOST /users/sign_in devise/ses...
Session is singularOnly one “authentication session” foreach user
Session Resource patternProposalGET /sessionPUT(POST) /session →sign inDELETE /session →sign outrest-pattern.hatenablog.co...
Singular resource in Railsresources :usersresource :user
resource :session
POST /session sessions#createGET /session/new sessions#newGET /session/edit sessions#editGET /session sessions#showPUT /se...
GET POST PUT DELETE/session show create update destroyin addition, “new” and “edit” as supplementary resources
GET POST PUT DELETE/session show create update destroyThis is also a pattern
Authlogicgithub.com/binarylogic/authlogicby Ben Johnson of Binary Logic
# app/models/session.rbclass Session < Authlogic::Session::Baseend
# app/models/session.rbclass Session < Authlogic::Session::BaseendIf they have no model, let them create it.(not an Active...
# app/controllers/sessions_controler.rbclass SessionsController < ApplicationController# POST /sessiondef create@session =...
resource :sessionRails way!!
I wish Devise were like that...I’m planning to do this...
AuthenticationSearchState changesExecution of procedural operationOperation to a list / SortWizard / Confirmation page
SearchSearch for users with the name thatcontains “tkawa”Search for users that were created before2012
Ransackgithub.com/ernie/ransackby Ernie Miller
GET /users?q[name_cont]=tkawaGET /users?q[created_at_lt]=2013-01-01
Search from collection= Filtering
Filtered Collection patternProposal/users?role=admin/users?since_id=123/users?page=2rest-pattern.hatenablog.com/entry/filte...
Kaminarigithub.com/amatsuda/kaminariby Akira MatsudaGET /users?page=2&per=10
I wish I could use query parameterslike models (w/ validation)...
class PostsController < ApplicationControllerprivatedef filter_params # using strong parameters@_filter_params ||= beginpa...
AuthenticationSearchState changesExecution of procedural operationOperation to a list / SortWizard / Confirmation page
WizardEnter data in multiple steps with pagetransitions
Wickedby Richard Schneemangithub.com/schneems/wicked
GET /user_steps/personalPUT /user_steps/personalGET /user_steps/socialPUT /user_steps/socialGET /user_steps/finish
Partial Resource patternProposal/users/1/personal/users/1/name,email/users/1?fields=name,emailrest-pattern.hatenablog.com/...
Transaction Resource patternProposalPOST /transactionsPUT /transactions/123PUT /transactions/123/committedrest-pattern.hat...
Rest of patterns are...ProposalFiltered SubresourceMulti-member ResourcePrivate Resource / Private NamespaceImplicit Colle...
Conclusion
RESTful patterns including “resources”are significantFocusing on these patterns encouragesgood resource designRubyGems are ...
If you are at a loss onresource modeling...Focus on gems’ patternYou will come up with the right resourceby referring to t...
If you are creating a gem...You should consider designing aroundresources, if possibleLets stick to the fundamentals of“re...
Thank you for your attention.Let me know if you discovermore patterns!rest-pattern.hatenablog.com
Upcoming SlideShare
Loading in...5
×

Rails Gems realize RESTful modeling patterns

5,165

Published on

RubyKaigi 2013
http://www.ustream.tv/recorded/33609885 (ja)

Published in: Technology

Transcript of "Rails Gems realize RESTful modeling patterns"

  1. 1. Rails Gems realize RESTfulmodeling patterns@tkawaRubyKaigi 2013, June 1
  2. 2. @tkawaRuby programmer (2000-)*RESTafarian (2005-)inspired by @yoheiRails programmer (2006-)*Sendagaya.rb (2012-)Toru KAWAMURA* with some blank of career
  3. 3. Sendagaya.rb 『千駄ヶ谷.rb』Every Monday 19:00 - 21:30
  4. 4. Sendagaya.rbOrganized by @ppworks, @fukajun, and meConcept: Looking forward to the weeklymeetup makes our everyday working funHeld currently at Shinjuku(!?), formerly atSendagaya#50 anniversary on June 3!sendagayarb.github.io
  5. 5. Rails Gems realize RESTfulmodeling patterns@tkawa
  6. 6. Rails Gems realize RESTfulresource modeling patterns@tkawa
  7. 7. Point of Departure
  8. 8. Rails is RESTful
  9. 9. Since RubyKaigi 2006June 11, 2006
  10. 10. # config/routes.rbFoobar::Application.routes.draw doresources :usersend
  11. 11. resources :users
  12. 12. GET /users users#indexPOST /users users#createGET /users/new users#newGET /users/:id/edit users#editGET /users/:id users#showPUT /users/:id users#updateDELETE /users/:id users#destroy$ rake routes
  13. 13. GET POST PUT DELETE/users index create - -/users/:id show - update destroyin addition, “new” and “edit” as supplementary resources
  14. 14. resources :usersThat’s it.That makes for really simple design.
  15. 15. REST’s advantage is...
  16. 16. SimpleConsistentTo reap the benefits ofHTTP (“HTTP way”)Generally:
  17. 17. Easy to designEasy to understandOn Rails “resources”particularly:
  18. 18. “resources” makes iteasy to designFor developer him/herself“resources” decides on a resource formAll you have to do is to decide on aresource name, such as “users”/user/1 /users/1 /users/user/1 /users/user-1
  19. 19. “resources” makes iteasy to understandFor developer him/herself, co-developer,and external developer (e.g. using API)Suggest that there are correspondingcontroller, model, view, etc, such asUsersController, User model
  20. 20. “resources” makes iteasy to design & understandRails has demonstrated thatthis simplicity goes well“Constraints are liberating”
  21. 21. You might think it does notgo well in these cases:
  22. 22. AuthenticationSearchState changesExecution of procedural operationOperation to a list / SortWizard / Confirmation page
  23. 23. AuthenticationSearchState changesExecution of procedural operationOperation to a list / SortWizard / Confirmation pageHow do I write routes.rb?How about Controller? Model?
  24. 24. We need another technique.But...
  25. 25. resources :users
  26. 26. GET POST PUT DELETE/users index create - -/users/:id show - update destroyin addition, “new” and “edit” as supplementary resources
  27. 27. GET POST PUT DELETE/users index create - -/users/:id show - update destroyThis is a pattern
  28. 28. “resources” makes iteasy to design & understand
  29. 29. A pattern makes iteasy to design & understand
  30. 30. “resources” is the fundamental patternIf there is a smaller and more concretepattern, we can design well accordinglyWe want more (concrete)patterns!
  31. 31. コストがかかるかもしれない問題解決を実際に行う前の先行調査として大変役に立つパターンには名前がついていることが重要である。なぜなら、名前がついていることで問題や解決策を記述したり、会話の中で取り上げたりすることができるようになるからであるja.wikipedia.org/wiki/デザインパターン_(ソフトウェア)A pattern is not a wild card,but a card with many benefits
  32. 32. Using a pattern is similarto Rails way, and...
  33. 33. We have “RubyGems”
  34. 34. Suppose a gem provides theimplementation of a specific patternThen routes.rb will be the description ofthe patterns to be used
  35. 35. Discover the patternfrom RubyGems
  36. 36. AuthenticationSearchState changesExecution of procedural operationOperation to a list / SortWizard / Confirmation page
  37. 37. Authentication“Sign in” / “Sign out”Those are represented as what?
  38. 38. devise.plataformatec.com.brDeviseby Plataformatec
  39. 39. GET /users/sign_in devise/sessions#newPOST /users/sign_in devise/sessions#createDELETE /users/sign_out devise/sessions#destroy…# config/routes.rbdevise_for :users
  40. 40. “Sessions” is a resource(that doesn’t involve a model)GET /users/sign_in devise/sessions#newPOST /users/sign_in devise/sessions#createDELETE /users/sign_out devise/sessions#destroy…# config/routes.rbdevise_for :users
  41. 41. Session is singularOnly one “authentication session” foreach user
  42. 42. Session Resource patternProposalGET /sessionPUT(POST) /session →sign inDELETE /session →sign outrest-pattern.hatenablog.com/entry/session-resource
  43. 43. Singular resource in Railsresources :usersresource :user
  44. 44. resource :session
  45. 45. POST /session sessions#createGET /session/new sessions#newGET /session/edit sessions#editGET /session sessions#showPUT /session sessions#updateDELETE /session sessions#destroy$ rake routes
  46. 46. GET POST PUT DELETE/session show create update destroyin addition, “new” and “edit” as supplementary resources
  47. 47. GET POST PUT DELETE/session show create update destroyThis is also a pattern
  48. 48. Authlogicgithub.com/binarylogic/authlogicby Ben Johnson of Binary Logic
  49. 49. # app/models/session.rbclass Session < Authlogic::Session::Baseend
  50. 50. # app/models/session.rbclass Session < Authlogic::Session::BaseendIf they have no model, let them create it.(not an ActiveRecord)
  51. 51. # app/controllers/sessions_controler.rbclass SessionsController < ApplicationController# POST /sessiondef create@session = Session.new(session_params)if @session.saveflash[:notice] = "Login successful!"redirect_back_or_default account_urlelserender :action => :newendendend
  52. 52. resource :sessionRails way!!
  53. 53. I wish Devise were like that...I’m planning to do this...
  54. 54. AuthenticationSearchState changesExecution of procedural operationOperation to a list / SortWizard / Confirmation page
  55. 55. SearchSearch for users with the name thatcontains “tkawa”Search for users that were created before2012
  56. 56. Ransackgithub.com/ernie/ransackby Ernie Miller
  57. 57. GET /users?q[name_cont]=tkawaGET /users?q[created_at_lt]=2013-01-01
  58. 58. Search from collection= Filtering
  59. 59. Filtered Collection patternProposal/users?role=admin/users?since_id=123/users?page=2rest-pattern.hatenablog.com/entry/filtered-collection
  60. 60. Kaminarigithub.com/amatsuda/kaminariby Akira MatsudaGET /users?page=2&per=10
  61. 61. I wish I could use query parameterslike models (w/ validation)...
  62. 62. class PostsController < ApplicationControllerprivatedef filter_params # using strong parameters@_filter_params ||= beginparams.default( # you can set default valueper: 10).permit(:date, :q, :page, :per).validate( # you can validate like a modeldate: { format: /Ad{4}-d{2}-d{2}Z/ },q: { length: { maximum: 20 } })endendhelper_method :filter_paramsendgithub.com/tkawa/collection_filterQuery parameters like models
  63. 63. AuthenticationSearchState changesExecution of procedural operationOperation to a list / SortWizard / Confirmation page
  64. 64. WizardEnter data in multiple steps with pagetransitions
  65. 65. Wickedby Richard Schneemangithub.com/schneems/wicked
  66. 66. GET /user_steps/personalPUT /user_steps/personalGET /user_steps/socialPUT /user_steps/socialGET /user_steps/finish
  67. 67. Partial Resource patternProposal/users/1/personal/users/1/name,email/users/1?fields=name,emailrest-pattern.hatenablog.com/entry/partial-resourceProvides only some attributes (fields)to GET/PUT
  68. 68. Transaction Resource patternProposalPOST /transactionsPUT /transactions/123PUT /transactions/123/committedrest-pattern.hatenablog.com/entry/transaction-resource
  69. 69. Rest of patterns are...ProposalFiltered SubresourceMulti-member ResourcePrivate Resource / Private NamespaceImplicit Collectionrest-pattern.hatenablog.com
  70. 70. Conclusion
  71. 71. RESTful patterns including “resources”are significantFocusing on these patterns encouragesgood resource designRubyGems are also useful for this purpose
  72. 72. If you are at a loss onresource modeling...Focus on gems’ patternYou will come up with the right resourceby referring to the design of a good gem“resources” is fundamentalDiverging from the “resources” is thelast resort
  73. 73. If you are creating a gem...You should consider designing aroundresources, if possibleLets stick to the fundamentals of“resources”And your gem will realize a pattern!
  74. 74. Thank you for your attention.Let me know if you discovermore patterns!rest-pattern.hatenablog.com
  1. A particular slide catching your eye?

    Clipping is a handy way to collect important slides you want to go back to later.

×