nedap rails workshop

of 193/193
Ruby on Rails

Post on 06-May-2015

1.510 views

Category:

Entertainment & Humor

3 download

Embed Size (px)

TRANSCRIPT

  • 1.Ruby on Rails

2. Hellow Bart Andr Dirkjan 3. Hellow Bart Andr Dirkjan 4. Laptops, apple 5. Development is more than coding 6. Ruby on Rails 7. Ruby on Rails 8. Language Ruby on Rails 9. Language Ruby on RailsFramework 10. What are we doing today? 1 Ruby basics 2Rails terminology / vision3 Build something simple 11. What are we doing today? 1 Ruby basics st .... ut firB 2Rails terminology / vision3 Build something simple 12. Very simple example 13. Address Book Generate a new Rails Application Generate some stuff Prepare the database Start the application View application and be excited! 14. Terminal 15. Terminal$ rails address_bookcreatecreate app/controllerscreate app/helperscreate app/modelscreate app/views/layoutscreate test/functionalcreate test/integration ...create log/server.logcreate log/production.logcreate log/development.logcreate log/test.log 16. Terminal$ rails address_bookcreatecreate app/controllerscreate app/helperscreate app/modelscreate app/views/layoutscreate test/functionalcreate test/integration ...create log/server.logcreate log/production.logcreate log/development.logcreate log/test.log$ cd address_book 17. Terminal 18. Terminal $ ./script/generate scaffold person name:stringexistsapp/controllers/existsapp/helpers/createapp/views/people... 19. ./script/destroy to undo Terminal $ ./script/generate scaffold person name:stringexistsapp/controllers/existsapp/helpers/createapp/views/people... 20. Terminal 21. Terminal$ rake db:migrate== 00000000000000 CreatePeople: migrating =============-- create_table(:people) -> 0.0177s== 00000000000000 CreatePeople: migrated (0.0180s) ==== 22. rake db:rollback to undo Terminal$ rake db:migrate== 00000000000000 CreatePeople: migrating =============-- create_table(:people) -> 0.0177s== 00000000000000 CreatePeople: migrated (0.0180s) ==== 23. N 24. Terminal 25. Terminal$ cd address_book 26. Terminal$ cd address_book $ ./script/server=> Booting Mongrel=> Rails 2.1.0 application starting on http://0.0.0.0:3000=> Call with -d to detach=> Ctrl-C to shutdown server** Starting Mongrel listening at 0.0.0.0:3000** Starting Rails with development environment...** Rails loaded.** Loading any Rails specific GemPlugins** Signals ready. TERM => stop. USR2 => restart.** Rails signals registered.** Mongrel 1.1.4 available at 0.0.0.0:3000** Use CTRL-C to stop. 27. http://localhost:3000/ 28. http://localhost:3000/people 29. It all seems like magic... 30. You feel lost... 31. This is normal. It will pass. 32. Close all 33. Ruby 34. The basics Objects Variables Methods Inheritance & Modules Blocks 35. Objects, variables & methods 36. Objects, variables & methodsclass Personattr_accessor :namedef insults(other, object=quot;cowquot;) quot;#{name} thinks #{other.name} is a stupid #{object}!quot; endend 37. class name Objects, variables & methodsclass Personattr_accessor :namedef insults(other, object=quot;cowquot;) quot;#{name} thinks #{other.name} is a stupid #{object}!quot; endend 38. class nameObjects, variables & methods instance variableclass Person attr_accessor :name def insults(other, object=quot;cowquot;)quot;#{name} thinks #{other.name} is a stupid #{object}!quot;end end 39. class nameObjects, variables & methods instance variableclass Personmethodattr_accessor :name def insults(other, object=quot;cowquot;)quot;#{name} thinks #{other.name} is a stupid #{object}!quot;end end 40. class Personattr_accessor :namedef insults(other, object=quot;cowquot;) quot;#{name} thinks #{other.name} is a stupid #{object}!quot; endendConsole: using a class 41. class Personattr_accessor :namedef insults(other, object=quot;cowquot;) quot;#{name} thinks #{other.name} is a stupid #{object}!quot; endendConsole: using a class>> andre = Person.new>> andre.name = Andre 42. class Personattr_accessor :namedef insults(other, object=quot;cowquot;) quot;#{name} thinks #{other.name} is a stupid #{object}!quot; endendConsole: using a class>> andre = Person.new>> andre.name = Andre>> bart = Person.new>> bart.name = Bart 43. class Personattr_accessor :namedef insults(other, object=quot;cowquot;) quot;#{name} thinks #{other.name} is a stupid #{object}!quot; endendConsole: using a class>> andre = Person.new>> andre.name = Andre>> bart = Person.new>> bart.name = Bart>> bart.insults(andre, dog) Bart thinks Andre is a stupid dog! 44. Inheritance class Personattr_accessor :nameend class Student < Person def insults(other, object=quot;cowquot;)quot;#{name} thinks #{other.name} is a stupid #{object}!quot;end end 45. Inheritance Student inheritsclass Personattr_accessor :namefrom personend class Student < Person def insults(other, object=quot;cowquot;)quot;#{name} thinks #{other.name} is a stupid #{object}!quot;end end 46. Modules 47. Person WomanMan 48. Driving skillPerson WomanMan 49. Driving skill Person Woman Man 50. PersonDriving skill WomanMan 51. Person WomanMan Driving skillAndre Bart 52. Modules module Insultingdef insults(other, object=quot;cowquot;) quot;#{name} thinks #{other.name} is a stupid #{object}!quot; endendclass Personattr_accessor :name include Insultingend 53. Creates an Modules Insulting module module Insultingdef insults(other, object=quot;cowquot;) quot;#{name} thinks #{other.name} is a stupid #{object}!quot; endendclass Personattr_accessor :name include Insultingend 54. Creates an Modules Insulting module module Insultingdef insults(other, object=quot;cowquot;) quot;#{name} thinks #{other.name} is a stupid #{object}!quot; end Person end classes can class PersonInsult attr_accessor :name include Insultingend 55. Creates an Modules Insulting module module Insultingdef insults(other, object=quot;cowquot;) quot;#{name} thinks #{other.name} is a stupid #{object}!quot; end Person end classes can class Person class RobotInsult attr_accessor :nameattr_accessor :name include Insultinginclude Insultingendend Everyone can insult now! 56. module Insultingdef insults(other, object=quot;cowquot;) quot;#{name} thinks #{other.name} is a stupid #{object}!quot; endendclass Person attr_accessor :name end Console: extending on the y 57. module Insultingdef insults(other, object=quot;cowquot;) quot;#{name} thinks #{other.name} is a stupid #{object}!quot; endendclass Person attr_accessor :name end Console: extending on the y>> andre = Person.new>> andre.name = Andre>> andre.extend(Insulting) nil 58. module Insultingdef insults(other, object=quot;cowquot;) quot;#{name} thinks #{other.name} is a stupid #{object}!quot; endendclass Person attr_accessor :name end Console: extending on the y>> andre = Person.new>> andre.name = Andre>> andre.extend(Insulting) nil>> andre.insults(bart) Andre thinks Bart is a stupid cow! 59. module Insultingdef insults(other, object=quot;cowquot;) quot;#{name} thinks #{other.name} is a stupid #{object}!quot; endendclass Person attr_accessor :name end Console: extending on the yWe could also extendan entire class like this! >> andre = Person.new>> andre.name = Andre>> andre.extend(Insulting) nil>> andre.insults(bart) Andre thinks Bart is a stupid cow! 60. Man Person Driving skill InsultingGardening 61. ManPerson Driving skill InsultingGardeningHow do we test if this man can insult? 62. Duck-typing 63. If it walks like a duck and quacks like a duck, it's a duck. Lisa Graves 64. andre.respond_to?(:insult) 65. Person WomanMan 66. Person WomanMan Driver 67. PersonDriving skill WomanMan 68. Blocks 69. class Personattr_accessor :nameendConsole: using blocks 70. class Personattr_accessor :nameendConsole: using blocks >> people[,] 71. class Personattr_accessor :nameendConsole: using blocks >> people[,]>> people.map{ |item| #{item.name} is kewl }[Andre is kewl, Bart is kewl] 72. class Personattr_accessor :nameendConsole: using blocks also have: select, reject and inject toWework with collections!>> people[,]>> people.map{ |item| #{item.name} is kewl }[Andre is kewl, Bart is kewl] 73. You know Ruby! 74. You know Ruby! Sorta... 75. You know Ruby! Sorta... 76. PART II 77. Convention over configuration 78. railsenvy.com 79. VIEWMVC MODELCONTROLLER 80. Models Talk to the database, contain business logic Controllers Provide the glue, prepare data when needed ViewsShow the content to the user 81. You are not a beautiful and unique snowflake. You are the same decaying organic matter as everyone else, and we are all a part of the same compost pile. Tyler Durden, Fight Club 82. SEECHANGERESOURCE ADDREMOVE 83. Show me somethingSEECHANGERESOURCE ADDREMOVE 84. Show me something SEE CHANGERESOURCEAdd someone ADDREMOVE 85. Show me something SEE CHANGEChangesomething RESOURCEAdd someone ADDREMOVE 86. Show me something SEE CHANGEChangesomething RESOURCEAdd someone Delete stuff ADDREMOVE 87. CREATEUPDATE CRUD READDELETE 88. CREATEUPDATE CRUD READDELETE 89. CREATEUPDATE CRUD READDELETE HTTP ! 90. POST CREATEUPDATE CRUD READDELETE HTTP ! 91. POST CREATEUPDATE CRUD READ GETDELETE HTTP ! 92. POSTPUT CREATEUPDATE CRUD READ GETDELETE HTTP ! 93. POSTPUT CREATEUPDATE CRUD READ GETDELETEDELETEHTTP ! 94. http://www.snowake.org/people/1 95. UNIVERSALURIIDE NTIFI ER RESOURCE 96. ADD POST /people 97. ADD POST /people SEE GET/people 98. ADDPOST /people SEEGET/people CHANGE PUT/people/1 99. ADDPOST /people SEEGET/people CHANGE PUT/people/1 REMOVE DELETE /people/1 100. REPRESENTATIONAL STATE TRANSFERREST 101. RAILS CONTROLLER ACTIONS 102. RAILS CONTROLLER ACTIONSINDEXNEW EDIT SHOW CREATEUPDATEDESTROY 103. Building something... 104. Lets get started 105. Choose a subject 106. 2 hrsIT WONT BE ENOUGH... 107. First 15 minutes You should have an idea You should have a rough sketch You should have thought of what models you need You should think of their relation to each other Pick an pair of models with a 1..* relationship1Student*Beer 108. Next 10 minutes You should have a new rails app $ rails [your_app_name] You should have generated the models $ ./script/generate scaffold [model_name] [attr]:[type type = string, text, integer, float, boolean,date, time, datetimereserved attrs => type, version 109. mate . 110. App structure - app - models - views - controllers - config - db - migrate 111. App structure - app - modelsthe model files - views - controllers - config - db - migrate 112. App structure - app - modelsthe model files - views templates for HTML - controllers - config - db - migrate 113. App structure - app - modelsthe model files - views templates for HTML - controllers the controller files - config - db - migrate 114. App structure - app - modelsthe model files - views templates for HTML - controllers the controller files - configbasic configuration - db - migrate 115. App structure - app - modelsthe model files - views templates for HTML - controllers the controller files - configbasic configuration - db - migrate database migrations 116. Migrations 117. db/migrate/00000000_create_people.rbclass CreatePeople < ActiveRecord::Migrationdef self.upcreate_table :people do |t|t.string :name t.timestampsendend def self.downdrop_table :peopleendend 118. Create a People db/migrate/00000000_create_people.rbtable on UPclass CreatePeople < ActiveRecord::Migrationdef self.upcreate_table :people do |t|t.string :name t.timestampsendend def self.downdrop_table :peopleendend 119. Create a Peopledb/migrate/00000000_create_people.rb With a Nametable on UPString class CreatePeople < ActiveRecord::Migration def self.up create_table :people do |t| t.string :namet.timestamps end enddef self.down drop_table :people end end 120. Create a Peopledb/migrate/00000000_create_people.rb With a Nametable on UPString class CreatePeople < ActiveRecord::Migration def self.up create_table :people do |t| t.string :namet.timestamps end enddef self.down drop_table :peopleAnd some time-stamps: end end created_at & updated_at 121. Create a Peopledb/migrate/00000000_create_people.rb With a Nametable on UPString class CreatePeople < ActiveRecord::Migration def self.up create_table :people do |t| t.string :namet.timestamps end enddef self.down drop_table :peopleAnd some time-stamps: end end created_at & updated_atDrop thetable onDOWN 122. Relationships 123. 1Student * Beer app/models/student.rbclass Student < ActiveRecord::Base has_many :beers end app/models/beer.rbclass Beer < ActiveRecord::Base belongs_to :student end 124. db/migrate/00000000_create_beers.rbclass CreateBeers < ActiveRecord::Migrationdef self.upcreate_table :beers do |t|t.string :brandt.references :studentt.timestampsendend def self.downdrop_table :beersendend 125. db/migrate/00000000_create_beers.rb Add a reference to Student(:student_id)class CreateBeers < ActiveRecord::Migrationdef self.upcreate_table :beers do |t|t.string :brandt.references :studentt.timestampsendend def self.downdrop_table :beersendend 126. Next 10 minutes You should update your model files when needed belongs_to, has_many, has_one, has_many :through You should add references to migrations t.references :student 127. Next 5 minutes You should have migrated the database $ rake db:migrate You should have a running server $ ./script/server You should see your app $ open http://localhost:3000 128. Routes 129. cong/routes.rb ActionController::Routing::Routes.draw do |map|map.resources :studentsmap.resources :beers # You can have the root of your site routed with map.root# map.root :controller => quot;welcomequot; map.connect ':controller/:action/:id'map.connect ':controller/:action/:id.:format'end 130. cong/routes.rbRoutes for each resourceActionController::Routing::Routes.draw do |map|map.resources :studentsmap.resources :beers # You can have the root of your site routed with map.root# map.root :controller => quot;welcomequot; map.connect ':controller/:action/:id'map.connect ':controller/:action/:id.:format'end 131. cong/routes.rbRoutes for each resourceActionController::Routing::Routes.draw do |map|map.resources :studentsmap.resources :beers # You can have the root of your site routed with map.root# map.root :controller => quot;welcomequot; map.connect ':controller/:action/:id'map.connect ':controller/:action/:id.:format'endRemove # andchange :controller to students 132. ADDPOST /people SEEGET/people CHANGE PUT/people/1 REMOVE DELETE /people/1 SEEGET/people/1 CHANGE GET/people/1/edit ADDGET/people/new 133. Next 5 minutes Change the routes Uncomment & choose default controller Remove public/index.html $ rm public/index.html Refresh your browser 134. ActiveRecord 135. One class per tableOne instance per row 136. One class per utable btes at trisare lumnCo One instance per row 137. Student.find_by_name(Andre)Student.find(:first, :conditions => [name = ?,Andre]) 138. Student.find_all_by_name(Andre)Student.find(:all, :conditions => [name = ?,Andre]) 139. andre = Student.new( :name => Andre ) andre.save 140. Next 10 minutes You should play with your app, create some instances We created a student named Andre You should start a console $ ./script/console You should build a few relationships using the console >> andre = Student.find_by_name(Andre)>> beer = andre.beers.create( :brand => Grolsch )>> beer.student.nameAndre 141. Views 142. app/views/beer/new.html.erb New beer


143. Title of the page app/views/beer/new.html.erb New beer


144. Title of the pageapp/views/beer/new.html.erb A formNew beer


145. Title of the pageapp/views/beer/new.html.erb A formNew beer


Show errors messages if

something goes wrong

146. Title of the page app/views/beer/new.html.erb A formNew beer


Show errors messages if

something goes wrong Some fields

and a button 147. Title of the page app/views/beer/new.html.erb A formNew beer


Show errors messages if

something goes wrong Some fields

and a button Back link 148. app/views/beer/new.html.erb New beer


149. app/views/beer/new.html.erbNew beer



150. Next 15 minutes Should be able to set a belongs_to relationship collection_select Relationship must be able to be set on new and existing objects Change both the edit and new view! Test that it really works! Try to edit the show view to represent the object relationship so another human understands it! 151. Validations This is a behaviour... 152. Validations This is a behaviour... 153. BDD BEHAVIOUR DRIVEN DEVELOPMENT 154. How should a student behave? 155. Student should never have a blank name 156. Terminal 157. Terminal$ ./script/generate rspeccreate lib/tasks/rspec.rakecreate script/autospeccreate script/speccreate script/spec_servercreate speccreate spec/rcov.optscreate spec/spec.optscreate spec/spec_helper.rbcreate storiescreate stories/all.rbcreate stories/helper.rb 158. Terminal$ ./script/generate rspeccreate lib/tasks/rspec.rakecreate script/autospeccreate script/speccreate script/spec_servercreate speccreate spec/rcov.optscreate spec/spec.optscreate spec/spec_helper.rbcreate storiescreate stories/all.rbcreate stories/helper.rb$ ./script/generate rspec_model student 159. Terminal$ ./script/generate rspeccreate lib/tasks/rspec.rakecreate script/autospeccreate script/speccreate script/spec_servercreate speccreate spec/rcov.optscreate spec/spec.optscreate spec/spec_helper.rbcreate storiescreate stories/all.rbcreate stories/helper.rb$ ./script/generate rspec_model student $ rake db:migrate RAILS_ENV=test 160. spec/models/student_spec.rbrequire File.dirname(__FILE__) + '/../spec_helper' describe Student doit quot;should never have a blank namequot; dono_name = Student.new( :name => )no_name.should_not be_valid end end 161. spec/models/student_spec.rb ActiveRecord objectsrequire File.dirname(__FILE__) + '/../spec_helper' describe Student dohave a valid? method it quot;should never have a blank namequot; dono_name = Student.new( :name => )no_name.should_not be_valid end end 162. require File.dirname(__FILE__) + '/../spec_helper'describe Student doit quot;should never have a blank namequot; dono_name = Student.new( :name => )no_name.should_not be_valid endend Terminal: Running tests 163. require File.dirname(__FILE__) + '/../spec_helper'describe Student doit quot;should never have a blank namequot; dono_name = Student.new( :name => )no_name.should_not be_valid endend Terminal: Running tests$ ruby spec/models/student_spec.rbF Failed:Student should never have a blank name (FAILED) Finished in 0.1 seconds 1 examples, 1 failures, 0 pending 164. app/models/student.rbclass Student < ActiveRecord::Base has_many :beers validates_presence_of :name end 165. app/models/student.rbclass Student < ActiveRecord::Base has_many :beers validates_presence_of :name end 166. Next 5 minutes Add Rspec to your project ./script/generate rspec Generate specs for your models - dont replace files! ./script/generate rspec_model [model-name] Clean spec files. Make sure they look like this. require File.dirname(__FILE__) + '/../spec_helper'describe Student doend Build the test database rake db:migrate RAILS_ENV=test 167. Next 15 minutes Spec out all your validations First, all your specs should fail Add the validations to your models validates_presence_of validates_uniqueness_of validates_format_of validates_length_of validates_numericality_of Then, all your specs should pass 168. Connecting dots 169. ............. Connecting dots 170. Lets make our view a little bit more fun 171. app/views/students/show.html.erb

Name:

| 172. app/views/students/show.html.erb

Name:

  • 1 x

| 173. Next 10 minutes Pimp one of your views! 174. You all get a PDF version of this book to continue working on your project,thanks to pragprog.com FREE! 175.