Intro to Ruby - Twin Cities Code Camp 7


Published on

Slides from my "Introduction to Ruby" talk at Twin Cities Code Camp 7 on 10/24/2009

Published in: Technology, Business
  • Be the first to comment

No Downloads
Total views
On SlideShare
From Embeds
Number of Embeds
Embeds 0
No embeds

No notes for slide
  • Hi everyone. I’m Brian. I do Ruby and Rails training and consulting.
  • Maybe you do... but it can be even more fun.
  • I hated programming. I did some when I was a kid, but it wasn’t what I wanted to do. I liked the web. And I started building sites in 1995 for small businesses.
  • so I started learning to program in ASP and eventually PHP. Even did some Java and some Oracle DBA stuff in there.
  • I was getting burned out, spending hours fighting with the languages while writing the same kind of applications over again.
  • A consultant who was working with me on a Java project introduced me to Rails
    and now, four years later,
  • I get to work on fun projects, work with amazing people, I’m excited about what I do, and I even got to write some books.
  • I want to get you excited about this language. I want to you to ask me any questions you have, and I want you to run home and start coding! So the best way to do that is to show you what you can do.
  • We can make a desktop application that works on Windows, Mac, and Linux using Shoes.
  • We can make a very simple iPhone-enabled website with Sinatra. This one serves files to you in around 50 lines of code.
  • We can use Sass to generate stylesheets for our applications. We can use variables for our colors and widths!
  • Use Rails. Rails is a great framework for building web applications. And despite what you’ve heard, it scales exceptionally well, as long as you know how to scale a web application and you’ve written good code.
  • Use Rails to kickstart a CMS.
  • Highly dynamic, high level, 100% object oriented, 100% open source, and really easy to learn.
  • Ruby was created by Yukihiro Matsumoto (Matz) in 1993. It’s built on C, and has many implementations, including JRuby, which runs on the JVM, and IronRuby, which runs on the .Net platform.
  • “How you feel is more important than what you do. “
    The entire language is designed for programmer productivity and fun.
  • Principle of Least Surprise - This means The language should behave in a way that is not confusing to experienced developers. It doesn’t mean that it works like your current favorite language! But as you get used to Ruby, you’ll find that you ramp up quickly.
  • Ruby achieves this through a consistant API. You won’t find yourself guessing too much what methods are available to you.
  • It also helps that the syntax is simple. There are no unnecessary semicolons or curly braces. The interpreter knows when lines end.
  • We have numbers, strings, multiplication, addition, subtraction, and division, just like everyone else.
  • The square brackets denote an array.
  • This is the hash symbol, or the hash rocket. Whenever you see this, you’re dealing with a hash.
  • When you see these, you’re looking at Symbols. They represent names and some strings. They conserve memory, as repeating a symbol in your code uses the same memory reference, whereas repeating a string creates a new object on each use.
  • Unless is an alias for “if not”. Subtle, but sometimes much more readable.
  • You can append these suffixes to statements to prevent them from firing. This is a great space saver and it’s easy to read
  • The two arrows (>>) is actually a method on the Date object that adds months. So here, we’re adding six months to the start date and comparing it to today

    Notice here that the input parameter is assumed to be a date. There’s no type checking here.
  • The = is part of the method name. And Ruby’s interpreter doesn’t mind you putting a space in front of it to make it easier to read!
  • Making getters and setters is so common that Ruby can do it for you.
  • It assumes you are an intelligent person who wants to get things done. It will not try to protect you from your own stupidity.
  • In fact,
  • Test All The Effing Time! Let’s go through adding our “on_probation?” method to our Person class. A person is on probation for the first six months of employment.
  • Here we have two tests, one using a person hired today, and another using a person last year.
  • Did we miss any cases?
  • Everything is an object in Ruby. There are no primitive types. Strings, integers, floats, everything. Even Nil, True, and False!
  • Everything. Even 0 and -1.
  • I’m not here to tell you that dynamically typed languages are better than statically typed languages. I prefer dynamic typing. I am more productive with it. And most of the claims against it are false.
  • We don’t need to specify a “return” keyword.
  • In this example, if the status is not closed, this method will return false. In Rails, if a before_save method returns false, the record won’t save to the database.
  • There are methods on arrays and hashes to iterate over the elements stored within.
  • Blocks let you pass code as a parameter, so that the code may be run within the method. If you’ve used closures or anonymous functions, you already understand this. But this is how Ruby developers work every day.
  • We can create modules of code that we can mix in to our classes.
  • In this example, we’re using modules to replace inheritence. However, since classes are objects, we can also apply modules to instances of objects at runtime.
  • If it walks like a duck, and talks like a duck, it’s a duck. Even if it’s not.
  • Declare modules that encapsulate behavior. Here we have a doctor, a ninja, and a musician.
  • We can then mix in the behaviors to the instance of the class. Its type doesn’t really matter. We can ask the instance if it has the methods we want and we can call them.
  • Reflection is built into the core language. It’s not a tacked on library, and it’s meant to be used to improve your code.
  • We can ask our model all sorts of questions, and even actually send messages dynamically.
  • We can loop over an array and generate methods on the object.
  • Sinatra is a simple web framework that basically maps incoming requests to backend code that produces responses.
  • That little bit of code gets us a working web application that handles requests.
  • We write stories using plain text, that describes what we want to do.
  • Intro to Ruby - Twin Cities Code Camp 7

    1. 1. intro to ruby brian hogan New Auburn Personal Computer Services LLC
    2. 2. programming is fun.
    3. 3. you just don’t know it yet.
    4. 4. I was a designer. I hated programming.
    5. 5. my clients wanted interactive websites...
    6. 6. and I started to hate my life.
    7. 7. I learned Ruby in 2005 and fell in love...
    8. 8. So what can kinds of things can you do with Ruby?
    9. 9. do para "Item name" @name = edit_line button "Add to list" do @names.append do para @name.text end @name.text = "" end button("Clear the list") {@names.clear} @names = stack :width=>"100%", :height=>"90%" end
    10. 10. require 'sinatra' require 'pathname' get "/" do dir = "./files/" @links = Dir[dir+"*"].map { |file| file_link(file) }.join erb :index end helpers do def file_link(file) filename = "<li><a href='#{file}' target='_self'>#{filename}</a></li>" end end use_in_file_templates! __END__ @@ index <html> <head> <meta name="viewport" content="width=320; initial-scale=1.0; maximum-scale=1.0; user-scalable=0;"/> <style type="text/css" media="screen">@import "/stylesheets/iui.css";</style> <script type="application/x-javascript" src="/javascripts/iui.js"></script> </head> <body> <div class="toolbar"> <h1 id="pageTitle"></h1> </div> <ul id="home" title="Your files, sir." selected="true"> <%= @links %> </ul> </body> </html>
    11. 11. !the_border = 1px !base_color = #111 #header { #header color: #333333; color = !base_color * 3 border-left: 1px; border-left= !the_border border-right: 2px; border-right = !the_border * 2 color: red; } color: red #header a { font-weight: bold; a text-decoration: none; } font-weight: bold text-decoration: none
    12. 12. got a great idea and want to get it out there quickly?
    13. 13. got a big site that’s hard to maintain?
    14. 14. So, what is Ruby? • Highly dynamic • Very high level • 100% object oriented • 100% open-source • Really easy to learn
    15. 15. History Smalltalk C++ Ruby Java VB 6 C# (1983) (1989) (1993) (1995) (1996) (2000)
    16. 16. Ruby follows the Principle of Least Surprise.
    17. 17. consistent API "Brian".length ["red", "green", "blue"].length [:first_name => "Brian", :last_name => "Hogan"].length User.find_all_by_last_name("Hogan").length
    18. 18. and a simple syntax age = 42 first_name = "Homer" start_date = 1980, 06, 05 annual_salary = 100000.00
    19. 19. Basic Ruby
    20. 20. Standard operators 5 + 5 10 * 10 "Hello" + "World" 25 / 5
    21. 21. Arrays colors = ["Red", "Green", "Blue"]
    22. 22. Hashes (Dictionaries) attributes = {:age => 25, :first_name => "Homer", :last_name => "Simpson"}
    23. 23. =>
    24. 24. :foo
    25. 25. Simple control logic if on_probation(start_date) puts "Yes" else puts "no" end
    26. 26. Unless if !current_user.admin? redirect_to "/login" end unless current_user.admin? redirect_to "/login" end
    27. 27. Conditionals as statement suffixes redirect_to "/login" unless current_user.admin?
    28. 28. Methods (functions) are simple too. # if start date + 6 months is > today def on_probation?(start_date) (start_date >> 6) > end
    29. 29. Classes are easy too. class Person @started_on = @name = "" def started_on=(date) @started_on = date end def started_on @started_on end end
    30. 30. Class instance variables are private class Person @started_on = Expose them through @name = "" accessor methods that def started_on=(date) @started_on = date resemble C# and VB end Property members. def started_on @started_on end person = person.age = 32 def name=(name) = "Brian" @name = name end person.age => 32 def name @name => "Brian" end end
    31. 31. Let Ruby write code for you! class Person @started_on = @name = "" def started_on=(date) class Person @started_on = date end attr_accessor :name attr_accessor :started_on def started_on @started_on end end def name=(name) @name = name end def name @name end end
    32. 32. Ruby is a loaded gun.
    33. 33. So, write good tests.
    34. 34. TATFT
    35. 35. def test_user_hired_today_should_be_on_probation person = person.hired_on = assert person.on_probation? end test_user_hired_last_year_should_not_be_on_probation person = person.hired_on = 1.year.ago assert !person.on_probation? end
    36. 36. Implement the method class Person attr_accessor :name, :start_date def on_probation? (start_date >> 6) > end end
    37. 37. And the tests pass.
    38. 38. Testing first helps you think about your design AND your features.
    39. 39. Every professional Ruby developer writes tests first for production code.
    40. 40. Ten Simple Rules For Programming in My Favorite Language.
    41. 41. 1. Everything is an object
    42. 42. 25.class Fixnum "brian".class String [1,2,3].class Array
    43. 43. 2. Everything evaluates to true except nil or false
    44. 44. x = 0 0 puts x if x x = -1 -1 puts x if x x = false nil puts x if x x = nil nil puts x if x
    45. 45. 3. Variables are dynamically typed but DATA is strongly typed!
    46. 46. age = 32 name = "Brian" TypeError: can't convert Fixnum into String name + age age = 32 name = "Brian" “Brian32” name + age.to_s
    47. 47. 4. Every method returns the last evaluation implicitly
    48. 48. def limit_reached? self.projects.length > 0 end def welcome_message if current_user.anonymous? "You need to log in." else "Welcome!" end end
    49. 49. 5. Every expression evaluates to an object
    50. 50. result = if current_user.anonymous? "You need to log in." else "Welcome!" end
    51. 51. It is very easy to accidentally return false! def before_save if self.status == "closed" self.closed_on = end end
    52. 52. 6. Classes are objects
    53. 53. WRONG! person = new Person RIGHT! person =
    54. 54. 7. You need to use and understand blocks.
    55. 55. Blocks can iterate roles.each do |role| puts "<li>" + + "<li>" end
    56. 56. They can also encapsulate code. ActiveRecord::Schema.define do create_table :pages do |t| t.string :name t.text :body t.timestamps end end
    57. 57. Every method can take a block! 5.times do puts "Hello!" end
    58. 58. 8. Favor modules over inheritance
    59. 59. module SharedValidations def self.included(base) base.validates_presence_of :name base.validates_uniqueness_of :name end end class Project class Task include SharedValidations include SharedValidations end end
    60. 60. Do not use type, use behaviors.
    61. 61. module Doctor module Ninja def treat_patient def attack puts "All better!" puts "You’re dead!" end end end end module Musician def play_guitar puts "meedily-meedily-meedily-meeeeeeeeee!" end end
    62. 62. person = person.extend Ninja "You're dead!" person.attack person.extend Doctor "All better!" person.treat_patient person.extend Musician "meedily-meedily- person.play_guitar meedily-meeeeeeeeee!"
    63. 63. 9. Embrace Reflection
    64. 64. person.respond_to?(:name) true person.respond_to?(:age) false person.send(:name) “Brian”
    65. 65. 10. Write code that writes code.
    66. 66. class User ROLES = ["admin", "superadmin", "user", "moderator"] ROLES.each do |role| class_eval <<-EOF def #{role}? self.roles.include?("#{role}") end EOF end end user = user.admin? user.moderator?
    67. 67. haml and sass
    68. 68. HAML !!! #wrapper.container_12 #header.grid_12 %h1 The awesome site %ul#navbar.grid_12 %li %a{:href => "index.html"} Home %li %a{:href => "products"} Products %li %a{:href => "services"} Services #middle.grid_12 %h2 Welcome #footer.grid_12 %p Copyright 2009 SomeCompany
    69. 69. HTML <div class='container_12' id='wrapper'> <div class='grid_12' id='header'> <h1>The awesome site</h1> </div> <ul class='grid_12' id='navbar'> <li> <a href='index.html'>Home</a> </li> <li> <a href='products'>Products</a> </li> <li> <a href='services'>Services</a> </li> </ul> <div class='grid_12' id='middle'> <h2>Welcome</h2> </div> <div class='grid_12' id='footer'> <p>Copyright 2009 SomeCompany</p> </div> </div>
    70. 70. SASS !the_border = 1px !base_color = #111 #header color = !base_color * 3 border-left= !the_border border-right = !the_border * 2 color: red a font-weight: bold text-decoration: none
    71. 71. CSS #header { color: #333333; border-left: 1px; border-right: 2px; color: red; } #header a { font-weight: bold; text-decoration: none; }
    72. 72. StaticMatic demo
    73. 73. sinatra
    74. 74. Hello Sinatra! require 'rubygems' require 'sinatra' get "/" do "Hello Sinatra!" end
    75. 75. Sinatra demo
    76. 76. cucumber
    77. 77. Feature: creating a new page in the wiki As an average anonymous user I want to create a page about Ruby So that I can tell everyone how awesome it is. Scenario: Creating a new page and editing its content Given I go to "/ruby" Then I should see "Edit this page" When I click "Edit this page" And I fill in "body" with "Ruby is the best programming language in the whole world!" And I press "Save" Then I should see "Ruby is the best programming language in the whole world!"
    78. 78. Testing the Wiki with Webrat and Cucumber
    79. 79. Ruby will make you productive.
    80. 80. And happy.
    81. 81. Resources: Try Ruby in your browser! Try SASS online: Try HAML online: Sinatra: Sinatra Wiki source: Cucumber: WATIR:
    82. 82. Questions? Twitter: bphogan bphogan at gmail