Ruby is Awesome

download Ruby is Awesome

of 182

  • date post

    10-May-2015
  • Category

    Technology

  • view

    1.300
  • download

    3

Embed Size (px)

description

Overview of the ruby language and bits of awesome it gives to developers

Transcript of Ruby is Awesome

  • 1.Ruby is AwesomeVitaly Kushner astrails.com

2. Interesting Times 3. Fast, Good, or Cheap. Pick two. 4. Fast, Good, or Cheap. Pick two. 5. Change Environment 6. Choose Language 7. Good Enough 8. You can do almost anything with any language 9. http://www.ickr.com/photos/jantik/254695220/ 10. Paul Graham http://paulgraham.com/ 11. Blub Language Paradox 12. BASIC wasGood Enough 13. No Recursion?! 14. Beating the averages http://paulgraham.com/avg.html 15. Lisp is good 16. Ruby is Better!:-) 17. Ruby is Practical 18. Ruby is an acceptable LISP 19. History 20. History Yukihiro Matsumoto (aka "Matz") 21. History Yukihiro Matsumoto (aka "Matz") Released in 1993 22. History Yukihiro Matsumoto (aka "Matz") Released in 1993 Got known in US about 2000 23. History Yukihiro Matsumoto (aka "Matz") Released in 1993 Got known in US about 2000 Gained momentum around 2003-2005 24. LISP+Smalltalk+ Python+Perl 25. Simple consistent syntax Dynamically typed Late binding Single Inheritance with Mixin support 26. Everything is an object Closures Garbage Collection Multi platform 27. Ruby is Awesome 28. Blocks 29. array.each { |e| puts }array.each { |e| puts e}array.each do |e|puts eend 30. map {|x| ...}collect {|x| ...}select{|x| ...}reject{|x| ...}find{|x| ...}any?{|x| ...}all?{|x| ...}sort{|a, b| ...} 31. File.readlines("foobar.dat").map{|l| l.strip}.sort {|x,y| x[-1] y[-1]}.map {|x| x.upcase}.to_xml 32. File.readlines("foobar.dat").map{|l| l.strip}.sort {|x,y| x[-1] y[-1]}.map {|x| x.upcase}.to_xml File.readlines("foobar.dat") 33. File.readlines("foobar.dat").map{|l| l.strip}.sort {|x,y| x[-1] y[-1]}.map {|x| x.upcase}.to_xml File.readlines("foobar.dat") .map {|line| line.strip} 34. File.readlines("foobar.dat").map{|l| l.strip}.sort {|x,y| x[-1] y[-1]}.map {|x| x.upcase}.to_xml File.readlines("foobar.dat") .map {|line| line.strip}.sort {|x,y| x.to_i y.to_i} 35. File.readlines("foobar.dat").map{|l| l.strip}.sort {|x,y| x[-1] y[-1]}.map {|x| x.upcase}.to_xml File.readlines("foobar.dat") .map {|line| line.strip}.sort {|x,y| x.to_i y.to_i}.map {|x| x.upcase} 36. File.readlines("foobar.dat").map{|l| l.strip}.sort {|x,y| x[-1] y[-1]}.map {|x| x.upcase}.to_xml File.readlines("foobar.dat") .map {|line| line.strip}.sort {|x,y| x.to_i y.to_i}.map {|x| x.upcase} .to_xml 37. class Hashdef to_html_attributesmap { |k, v|k + =" + v + "}.join( )endend 38. attrs = {:src => "foo.img",:width => 100,:height => 200,:class => "avatar"}attrs.to_html_attributes=> class="avatar" height="200" width="100" src="foo.img" 39. Closures 40. class Arraydef has_any_bigger_then(x)any? {|e| e > x}endend 41. def incrementor(x)proc {|y| y + x}endinc1 = incrementor(1)inc5 = incrementor(5) 42. def incrementor(x)proc {|y| y + x}endinc1 = incrementor(1)inc1.call(1)=> 2inc1.call(3)=> 4 43. def incrementor(x)proc {|y| y + x}endinc5 = incrementor(5)inc5.call(1)=> 6inc5.call(3)=> 8 44. # rubydef paidMore(amount)proc {|e| e.salary > amount}end// C#public PredicatePaidMore(int amount) {return delegate(Employee e) {return e.Salary > amount;}} 45. Meta Programming 46. Extending the languageto create new abstractions 47. Monkey Patching 48. class Hashdef to_html_attributesmap { |k, v|k + =" + v + "}.join( )endend 49. attrs = {:src => "foo.img",:width => 100,:height => 200,:class => "avatar"}attrs.to_html_attributes=> class="avatar" height="200" width="100" src="foo.img" 50. 3.megabytes=> 3145728 51. 10.months.from_now=> Thu Aug 12 03:25:40 0300 2010 52. 5.minutes.ago=> Mon Oct 12 03:21:02 0200 2009 53. Duck Typing 54. .to_s [1, 2, 3].to_s=> "123" 55. .to_s123.to_s=> "123" 56. .to_s"123".to_s=> "123" 57. "a#{b}c""a" + b.to_s + c 58. method_missing 59. NoMethodError 60. User.nd_by_company("Astrails") 61. User.nd_by_name_and_company( "Vitaly Kushner", "Astrails") 62. Multiple inheritance is evil:-) 63. Modules a.k.a. Mixins 64. module FlyHomedef set_home@home = positionenddef fly_homefly(@home)endend 65. class Bird < Livinginclude FlyHomedef fly(direction) ...def position ...endclass Airplane < Machineinclude FlyHomedef fly(direction) ...def position ...end 66. DSLDomain Specic Language 67. class User < ActiveRecord::Basehas_many :projectsbelongs_to :accounthas_many :reports,:class_name => "User",:foreign_key => :reports_to_idnamed_scope :activated,:conditions =>"activated_at IS NOT NULL"validates_uniqueness_of :namevalidates_presence_of :crypted_passwordvalidates_acceptance_of :terms_of_serviceend 68. safe dolocal { path "/backup/:kind" }s3 :key => YOUR_S3_KEY,:secret => YOUR_S3_SECRET,:bucket => S3_BUCKET,:path => ":kind/"gpg :password => "foobar" mysqldump do options "-ceKq --single-transaction --create-options" user "astrails" password "foobar"database :blogdatabase :astrails_com doskip_tables :request_logsendend tar do archive "etc-files" do files "/etc" end endend 69. safe dolocal { path "/backup/:kind" }s3 :key => YOUR_S3_KEY,:secret => YOUR_S3_SECRET,:bucket => S3_BUCKET,:path => ":kind/"gpg :password => "foobar"...end 70. safe do...mysqldump dooptions "-ceKq ..."user "astrails"password "foobar"database :blogdatabase :astrails_com doskip_tables :request_logsendend...end 71. safe do...tar doarchive "etc-files" dofiles "/etc"endendend 72. Rubygems 73. ~sudogeminstallastrailssafeSuccessfullyinstalledastrailssafe0.2.31geminstalledInstallingridocumentationforastrailssafe0.2.3...InstallingRDocdocumentationforastrailssafe0.2.3...~ 74. Rubyforge.org 8,426 gems 75. Github.com7,483 gems 76. Rails 77. http://www.ickr.com/photos/ecstaticist/2589723846/ 78. Rails is Fun 79. optimized forprogrammers happinessand sustainableproductivity 80. MVC 81. MVC Model 82. MVCModel View 83. MVCModel View Controller 84. convention over conguration 85. class User < ActiveRecord::Baseend 86. User.find(123)=> SELECT * FROM `users` WHERE (`users`.`id` = 123) 87. class User < ActiveRecord::Basebelongs_to :accounthas_many :projectsendclass UsersController < ApplicationControllerdef show@user = User.find(params[:user])render :template => showendend 88. class User < ActiveRecord::Basebelongs_to :accounthas_many :projectsendclass UsersController < ApplicationControllerdef show@user = User.find(params[:user])render :template => showendend 89. class User < ActiveRecord::Basebelongs_to :accounthas_many :projectsendclass UsersController < ApplicationControllerdef show@user = User.find(params[:user])endend 90. Models 91. http://www.ickr.com/photos/slyadnev/3959052112/ 92. ActiveRecord 93. ORMObject-Relational Mapping 94. MySQL PostgreSQL MSSql SQLite Oracle ODBC 95. Associationsclass User < ActiveRecord::Basehas_many :projectsendclass Project < ActiveRecord::Basebelongs_to :userend 96. u = User.find(1)=> SELECT * FROM `users` WHERE (`users`.`id` = 1) 97. u.projects.count=> SELECT count(*) AS count_all FROM `projects` WHERE(`projects`.user_id = 1) 98. User.find_by_first_name("Vitaly", :include => :projects)=> SELECT * FROM `users` WHERE(`users`.`first_name` = Vitaly) LIMIT 1=> SELECT `projects`.* FROM `projects` WHERE(`projects`.user_id = 1) 99. Project.first.user=> SELECT * FROM `projects` LIMIT 1=> SELECT * FROM `users` WHERE (`users`.`id` = 1) 100. Callbacks before_validation before_validation_on_create after_validation after_validation_on_create before_save before_create after_create after_save 101. Callbacks before_validation before_validation_on_create after_validation after_validation_on_create before_save before_create after_create after_save 102. class User < ActiveRecord::Basebefore_save :encrypt_passwordattr_accessor :passwordprivatedef enctypt_passwordunless password.blank?self.salt ||= ActiveSupport::SecureRandom.hex(40)self.crypted_password = encrypt(password, salt)endendend 103. Validations 104. validates_presence_of :account_idvalidates_uniqueness_of :namevalidates_numericality_of :ccvdef validateunless name[0] == ?Aerrors.add(:name, "Names must start with an A")endend 105. ActiveSupport 106. 3.days.ago[1,2,3].to_json2.weeks.from_nowhash.slice(:foo, :bar) 107. Controllers 108. http://www.ickr.com/photos/benjamin-nagel/2902721172/ 109. class UsersController < ApplicationControllerdef index@users = User.paginate(:page => params[:page],:per_page => 20)endend 110. http://yourdomain/users/index 111. http://localhost:3000/users/index 112. ActionController::Routing::Routes.draw do |map|map.connect :controller/:action/:idmap.connect :controller/:action/:id.:formatend 113. ActionController::Routing::Routes.draw do |map|map.connect :controller/:action/:idmap.connect :controller/:action/:id.:formatend /welcome/home :controller => welcome :action => home 114. ActionController::Routing::Routes.draw do |map|map.connect :controller/:action/:idmap.connect :controller/:action/:id.:formatend /users/edit/123 :controller => users :action => edit :id => 123 115. ActionController::Routing::Routes.draw do |map|map.connect :controller/:action/:idmap.connect :controller/:action/:id.:formatend projects/show/456.xml :controller => projects :action => show :id => 456 :format => xml 116. /talks/create?title=ruby%20is%20awsome&author[name]=Vitaly&author[company]=Astrails{:controller => talks,:action => create,:title => "ruby is awesome",:user => {:name => Vitaly,:company => Astrails}} 117. REST 118. RESTRepresentational State Transfer 119. HEAD GET POST PUT DELETE 120. index edit new update create destroy show 121. indexGET /users 122. newGET /users/new 123. createPOST /users 124. showGET /users/123 125. editGET /users/123/edit 126. updatePUT /users/123 127. destroyDELETE /users/123 128. map.resources :users do |user|user.resources :projectsendGET /users/123/projects :controller => :projects, :action => :index, :user_id => 123GET /users/123/projects/456 :controller => :projects, :action => :show, :user_id => 123, :id => 456 129. users_