Successfully reported this slideshow.
We use your LinkedIn profile and activity data to personalize ads and to show you more relevant ads. You can change your ad preferences anytime.
intro to ruby
                              brian hogan
               New Auburn Personal Computer Services LLC




twitt...
programming is fun.


twitter: bphogan
email: brianhogan at napcs.com
you just don’t know it
                     yet.

twitter: bphogan
email: brianhogan at napcs.com
I was a designer. I hated
              programming.

twitter: bphogan
email: brianhogan at napcs.com
my clients wanted
             interactive websites...

twitter: bphogan
email: brianhogan at napcs.com
and I started to hate
                     my life.


twitter: bphogan
email: brianhogan at napcs.com
I learned Ruby in 2005
               and fell in love...

twitter: bphogan
email: brianhogan at napcs.com
twitter: bphogan
email: brianhogan at napcs.com
So what can kinds of
           things can you do with
                    Ruby?

twitter: bphogan
email: brianhogan at na...
Shoes.app do
    para "Item name"
    @name = edit_line

    button "Add to list" do
     @names.append do
      para @nam...
require 'sinatra'
require 'pathname'

get "/" do
 dir = "./files/"
 @links = Dir[dir+"*"].map { |file|
   file_link(file)
...
!the_border = 1px
     !base_color = #111
                                        #header {
     #header                  ...
got a great idea and
         want to get it out there
                quickly?

twitter: bphogan
email: brianhogan at nap...
twitter: bphogan
email: brianhogan at napcs.com
got a big site that’s hard
               to maintain?

twitter: bphogan
email: brianhogan at napcs.com
twitter: bphogan
email: brianhogan at napcs.com
So, what is Ruby?
• Highly dynamic
• Very high level
• 100% object oriented
• 100% open-source
• Really easy to learn
History

    Smalltalk          C++         Ruby     Java     VB 6      C#
     (1983)           (1989)      (1993)   (199...
twitter: bphogan
email: brianhogan at napcs.com
Ruby follows the
                    Principle of Least
                        Surprise.

twitter: bphogan
email: brianho...
consistent API
"Brian".length
["red", "green", "blue"].length
[:first_name => "Brian", :last_name => "Hogan"].length
User....
and a simple syntax
age = 42
first_name = "Homer"
start_date = Date.new 1980, 06, 05
annual_salary = 100000.00
Basic Ruby


twitter: bphogan
email: brianhogan at napcs.com
Standard operators


 5 + 5
 10 * 10
 "Hello" + "World"
 25 / 5
Arrays


colors = ["Red", "Green", "Blue"]
Hashes (Dictionaries)


attributes = {:age => 25,
              :first_name => "Homer",
              :last_name => "Simps...
=>
:foo


twitter: bphogan
email: brianhogan at napcs.com
Simple control logic
if on_probation(start_date)
  puts "Yes"
else
  puts "no"
end
Unless
if !current_user.admin?
  redirect_to "/login"
end




unless current_user.admin?
  redirect_to "/login"
end
Conditionals as statement suffixes

redirect_to "/login" unless current_user.admin?
Methods (functions) are simple too.


 # if start date + 6 months is > today
 def on_probation?(start_date)
   (start_date...
Classes are easy too.
class Person
  @started_on = Date.today
  @name = ""

  def started_on=(date)
    @started_on = date...
Class instance variables are private
class Person
  @started_on = Date.today
                               Expose them th...
Let Ruby write code for you!
class Person
  @started_on = Date.today
  @name = ""

  def started_on=(date)
               ...
Ruby is a loaded gun.


twitter: bphogan
email: brianhogan at napcs.com
So, write good tests.


twitter: bphogan
email: brianhogan at napcs.com
TATFT


twitter: bphogan
email: brianhogan at napcs.com
def test_user_hired_today_should_be_on_probation
  person = Person.new
  person.hired_on = Date.today
  assert person.on_p...
Implement the method
class Person
  attr_accessor :name, :start_date

  def on_probation?
    (start_date >> 6) > Date.tod...
And the tests pass.


twitter: bphogan
email: brianhogan at napcs.com
Testing first helps you
         think about your design
           AND your features.

twitter: bphogan
email: brianhogan ...
Every professional Ruby
         developer writes tests
          first for production
                 code.
twitter: bpho...
Ten Simple Rules
 For Programming in
My Favorite Language.
1. Everything is an
                         object


twitter: bphogan
email: brianhogan at napcs.com
25.class     Fixnum



"brian".class   String



[1,2,3].class   Array
2. Everything evaluates
            to true except nil or
                    false

twitter: bphogan
email: brianhogan at...
x = 0
              0
puts x if x



x = -1
              -1
puts x if x



x = false
              nil
puts x if x



x =...
3. Variables are
          dynamically typed but
         DATA is strongly typed!

twitter: bphogan
email: brianhogan at n...
age = 32
name = "Brian"    TypeError: can't convert Fixnum into String
name + age




age = 32
name = "Brian"             ...
4. Every method
                  returns the last
                evaluation implicitly

twitter: bphogan
email: brianhog...
def limit_reached?
  self.projects.length > 0
end


def welcome_message
  if current_user.anonymous?
    "You need to log ...
5. Every expression
            evaluates to an object


twitter: bphogan
email: brianhogan at napcs.com
result = if current_user.anonymous?
           "You need to log in."
         else
           "Welcome!"
         end
It is very easy to accidentally return false!
       def before_save
         if self.status == "closed"
           self.c...
6. Classes are objects


twitter: bphogan
email: brianhogan at napcs.com
WRONG!
person = new Person




    RIGHT!
person = Person.new
7. You need to use and
             understand blocks.

twitter: bphogan
email: brianhogan at napcs.com
Blocks can iterate


roles.each do |role|
  puts "<li>" + role.name + "<li>"
end
They can also encapsulate code.



  ActiveRecord::Schema.define do
    create_table :pages do |t|
      t.string :name
  ...
Every method can take a block!




      5.times do
        puts "Hello!"
      end
8. Favor modules over
                  inheritance


twitter: bphogan
email: brianhogan at napcs.com
module SharedValidations
         def self.included(base)
           base.validates_presence_of :name
           base.vali...
Do not use type,
                     use behaviors.


twitter: bphogan
email: brianhogan at napcs.com
twitter: bphogan
email: brianhogan at napcs.com
module Doctor            module Ninja
  def treat_patient        def attack
    puts "All better!"       puts "You’re dead...
person = Person.new
person.extend Ninja      "You're dead!"
person.attack


person.extend Doctor
                         ...
9. Embrace Reflection


twitter: bphogan
email: brianhogan at napcs.com
person.respond_to?(:name)   true




person.respond_to?(:age)    false




person.send(:name)          “Brian”
10. Write code that
                    writes code.

twitter: bphogan
email: brianhogan at napcs.com
class User
  ROLES = ["admin", "superadmin", "user", "moderator"]
  ROLES.each do |role|
    class_eval <<-EOF
      def #...
haml and sass


twitter: bphogan
email: brianhogan at napcs.com
HAML
!!!
#wrapper.container_12
  #header.grid_12
    %h1 The awesome site
  %ul#navbar.grid_12
    %li
      %a{:href => "...
HTML
<div class='container_12' id='wrapper'>
   <div class='grid_12' id='header'>
     <h1>The awesome site</h1>
   </div>...
SASS

!the_border = 1px
!base_color = #111

#header
  color = !base_color * 3
  border-left= !the_border
  border-right = ...
CSS

#header {
  color: #333333;
  border-left: 1px;
  border-right: 2px;
  color: red; }

 #header a {
   font-weight: bo...
StaticMatic demo


twitter: bphogan
email: brianhogan at napcs.com
sinatra


twitter: bphogan
email: brianhogan at napcs.com
Hello Sinatra!


require 'rubygems'
require 'sinatra'

get "/" do
  "Hello Sinatra!"
end
Sinatra demo


twitter: bphogan
email: brianhogan at napcs.com
cucumber


twitter: bphogan
email: brianhogan at napcs.com
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 tel...
Testing the Wiki with
          Webrat and Cucumber


twitter: bphogan
email: brianhogan at napcs.com
Ruby will make you
                   productive.


twitter: bphogan
email: brianhogan at napcs.com
And happy.


twitter: bphogan
email: brianhogan at napcs.com
Resources:
 Try Ruby in your browser! http://tryruby.sophrinix.com/
         Try SASS online: http://sass-lang.com/try.htm...
Questions?
             Twitter: bphogan
         brianhogan at napcs.com

twitter: bphogan
email: brianhogan at napcs.com
Intro to Ruby
Upcoming SlideShare
Loading in …5
×

Intro to Ruby

2,690 views

Published on

Chippew Valley Code Camp 2009 talk. Very similar to the slides from Twin Cities Code Camp 7.

Published in: Technology
  • Be the first to comment

Intro to Ruby

  1. 1. intro to ruby brian hogan New Auburn Personal Computer Services LLC twitter: bphogan email: brianhogan at napcs.com
  2. 2. programming is fun. twitter: bphogan email: brianhogan at napcs.com
  3. 3. you just don’t know it yet. twitter: bphogan email: brianhogan at napcs.com
  4. 4. I was a designer. I hated programming. twitter: bphogan email: brianhogan at napcs.com
  5. 5. my clients wanted interactive websites... twitter: bphogan email: brianhogan at napcs.com
  6. 6. and I started to hate my life. twitter: bphogan email: brianhogan at napcs.com
  7. 7. I learned Ruby in 2005 and fell in love... twitter: bphogan email: brianhogan at napcs.com
  8. 8. twitter: bphogan email: brianhogan at napcs.com
  9. 9. So what can kinds of things can you do with Ruby? twitter: bphogan email: brianhogan at napcs.com
  10. 10. Shoes.app 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 twitter: bphogan email: brianhogan at napcs.com
  11. 11. 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 = Pathname.new(file).basename "<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> twitter: bphogan email: brianhogan at napcs.com
  12. 12. !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 twitter: bphogan email: brianhogan at napcs.com
  13. 13. got a great idea and want to get it out there quickly? twitter: bphogan email: brianhogan at napcs.com
  14. 14. twitter: bphogan email: brianhogan at napcs.com
  15. 15. got a big site that’s hard to maintain? twitter: bphogan email: brianhogan at napcs.com
  16. 16. twitter: bphogan email: brianhogan at napcs.com
  17. 17. So, what is Ruby? • Highly dynamic • Very high level • 100% object oriented • 100% open-source • Really easy to learn
  18. 18. History Smalltalk C++ Ruby Java VB 6 C# (1983) (1989) (1993) (1995) (1996) (2000) twitter: bphogan email: brianhogan at napcs.com
  19. 19. twitter: bphogan email: brianhogan at napcs.com
  20. 20. Ruby follows the Principle of Least Surprise. twitter: bphogan email: brianhogan at napcs.com
  21. 21. consistent API "Brian".length ["red", "green", "blue"].length [:first_name => "Brian", :last_name => "Hogan"].length User.find_all_by_last_name("Hogan").length
  22. 22. and a simple syntax age = 42 first_name = "Homer" start_date = Date.new 1980, 06, 05 annual_salary = 100000.00
  23. 23. Basic Ruby twitter: bphogan email: brianhogan at napcs.com
  24. 24. Standard operators 5 + 5 10 * 10 "Hello" + "World" 25 / 5
  25. 25. Arrays colors = ["Red", "Green", "Blue"]
  26. 26. Hashes (Dictionaries) attributes = {:age => 25, :first_name => "Homer", :last_name => "Simpson"}
  27. 27. =>
  28. 28. :foo twitter: bphogan email: brianhogan at napcs.com
  29. 29. Simple control logic if on_probation(start_date) puts "Yes" else puts "no" end
  30. 30. Unless if !current_user.admin? redirect_to "/login" end unless current_user.admin? redirect_to "/login" end
  31. 31. Conditionals as statement suffixes redirect_to "/login" unless current_user.admin?
  32. 32. Methods (functions) are simple too. # if start date + 6 months is > today def on_probation?(start_date) (start_date >> 6) > Date.today end
  33. 33. Classes are easy too. class Person @started_on = Date.today @name = "" def started_on=(date) @started_on = date end def started_on @started_on end end
  34. 34. Class instance variables are private class Person @started_on = Date.today 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.new person.age = 32 def name=(name) person.name = "Brian" @name = name end person.age => 32 def name person.name @name => "Brian" end end
  35. 35. Let Ruby write code for you! class Person @started_on = Date.today @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
  36. 36. Ruby is a loaded gun. twitter: bphogan email: brianhogan at napcs.com
  37. 37. So, write good tests. twitter: bphogan email: brianhogan at napcs.com
  38. 38. TATFT twitter: bphogan email: brianhogan at napcs.com
  39. 39. def test_user_hired_today_should_be_on_probation person = Person.new person.hired_on = Date.today assert person.on_probation? end test_user_hired_last_year_should_not_be_on_probation person = Person.new person.hired_on = 1.year.ago assert !person.on_probation? end
  40. 40. Implement the method class Person attr_accessor :name, :start_date def on_probation? (start_date >> 6) > Date.today end end
  41. 41. And the tests pass. twitter: bphogan email: brianhogan at napcs.com
  42. 42. Testing first helps you think about your design AND your features. twitter: bphogan email: brianhogan at napcs.com
  43. 43. Every professional Ruby developer writes tests first for production code. twitter: bphogan email: brianhogan at napcs.com
  44. 44. Ten Simple Rules For Programming in My Favorite Language.
  45. 45. 1. Everything is an object twitter: bphogan email: brianhogan at napcs.com
  46. 46. 25.class Fixnum "brian".class String [1,2,3].class Array
  47. 47. 2. Everything evaluates to true except nil or false twitter: bphogan email: brianhogan at napcs.com
  48. 48. 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
  49. 49. 3. Variables are dynamically typed but DATA is strongly typed! twitter: bphogan email: brianhogan at napcs.com
  50. 50. age = 32 name = "Brian" TypeError: can't convert Fixnum into String name + age age = 32 name = "Brian" “Brian32” name + age.to_s
  51. 51. 4. Every method returns the last evaluation implicitly twitter: bphogan email: brianhogan at napcs.com
  52. 52. def limit_reached? self.projects.length > 0 end def welcome_message if current_user.anonymous? "You need to log in." else "Welcome!" end end
  53. 53. 5. Every expression evaluates to an object twitter: bphogan email: brianhogan at napcs.com
  54. 54. result = if current_user.anonymous? "You need to log in." else "Welcome!" end
  55. 55. It is very easy to accidentally return false! def before_save if self.status == "closed" self.closed_on = Date.today end end
  56. 56. 6. Classes are objects twitter: bphogan email: brianhogan at napcs.com
  57. 57. WRONG! person = new Person RIGHT! person = Person.new
  58. 58. 7. You need to use and understand blocks. twitter: bphogan email: brianhogan at napcs.com
  59. 59. Blocks can iterate roles.each do |role| puts "<li>" + role.name + "<li>" end
  60. 60. They can also encapsulate code. ActiveRecord::Schema.define do create_table :pages do |t| t.string :name t.text :body t.timestamps end end
  61. 61. Every method can take a block! 5.times do puts "Hello!" end
  62. 62. 8. Favor modules over inheritance twitter: bphogan email: brianhogan at napcs.com
  63. 63. 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
  64. 64. Do not use type, use behaviors. twitter: bphogan email: brianhogan at napcs.com
  65. 65. twitter: bphogan email: brianhogan at napcs.com
  66. 66. 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
  67. 67. person = Person.new 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!"
  68. 68. 9. Embrace Reflection twitter: bphogan email: brianhogan at napcs.com
  69. 69. person.respond_to?(:name) true person.respond_to?(:age) false person.send(:name) “Brian”
  70. 70. 10. Write code that writes code. twitter: bphogan email: brianhogan at napcs.com
  71. 71. 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.new user.admin? user.moderator?
  72. 72. haml and sass twitter: bphogan email: brianhogan at napcs.com
  73. 73. 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
  74. 74. 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>
  75. 75. 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
  76. 76. CSS #header { color: #333333; border-left: 1px; border-right: 2px; color: red; } #header a { font-weight: bold; text-decoration: none; }
  77. 77. StaticMatic demo twitter: bphogan email: brianhogan at napcs.com
  78. 78. sinatra twitter: bphogan email: brianhogan at napcs.com
  79. 79. Hello Sinatra! require 'rubygems' require 'sinatra' get "/" do "Hello Sinatra!" end
  80. 80. Sinatra demo twitter: bphogan email: brianhogan at napcs.com
  81. 81. cucumber twitter: bphogan email: brianhogan at napcs.com
  82. 82. 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!" twitter: bphogan email: brianhogan at napcs.com
  83. 83. Testing the Wiki with Webrat and Cucumber twitter: bphogan email: brianhogan at napcs.com
  84. 84. Ruby will make you productive. twitter: bphogan email: brianhogan at napcs.com
  85. 85. And happy. twitter: bphogan email: brianhogan at napcs.com
  86. 86. Resources: Try Ruby in your browser! http://tryruby.sophrinix.com/ Try SASS online: http://sass-lang.com/try.html Try HAML online: http://haml-lang.com/try.html http://staticmatic.rubyforge.org/ Sinatra: http://www.sinatrarb.com/ Sinatra Wiki source: http://github.com/napcs/sinatriki Cucumber: http://cukes.info/ WATIR: http://watir.com/ twitter: bphogan email: brianhogan at napcs.com
  87. 87. Questions? Twitter: bphogan brianhogan at napcs.com twitter: bphogan email: brianhogan at napcs.com

×