This document provides an introduction to the Ruby programming language from Brian Hogan. It discusses Hogan's background as a designer who grew to love programming after learning Ruby. It provides overviews of common Ruby concepts like objects, variables, classes and testing. It also demonstrates examples of Ruby code and highlights libraries like Haml, Sass, Sinatra and Cucumber. The overall message is that Ruby can make developers productive and happy. Resources are included for trying Ruby online.
9. So what can kinds of
things can you do with
Ruby?
twitter: bphogan
email: brianhogan at napcs.com
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. 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
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. 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. 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. 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. Ruby is a loaded gun.
twitter: bphogan
email: brianhogan at napcs.com
37. So, write good tests.
twitter: bphogan
email: brianhogan at napcs.com
62. 8. Favor modules over
inheritance
twitter: bphogan
email: brianhogan at napcs.com
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. Do not use type,
use behaviors.
twitter: bphogan
email: brianhogan at napcs.com
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. 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!"
70. 10. Write code that
writes code.
twitter: bphogan
email: brianhogan at napcs.com
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?
83. 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
84. Testing the Wiki with
Webrat and Cucumber
twitter: bphogan
email: brianhogan at napcs.com
85. Ruby will make you
productive.
twitter: bphogan
email: brianhogan at napcs.com
87. 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
88. Questions?
Twitter: bphogan
brianhogan at napcs.com
twitter: bphogan
email: brianhogan at napcs.com
Notas del editor
Hi everyone. I&#x2019;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&#x2019;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&#x2019;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&#x2019;ve heard, it scales exceptionally well, as long as you know how to scale a web application and you&#x2019;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&#x2019;s built on C, and has many implementations, including JRuby, which runs on the JVM, and IronRuby, which runs on the .Net platform.
&#x201C;How you feel is more important than what you do. &#x201C;
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&#x2019;t mean that it works like your current favorite language! But as you get used to Ruby, you&#x2019;ll find that you ramp up quickly.
Ruby achieves this through a consistant API. You won&#x2019;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&#x2019;re dealing with a hash.
When you see these, you&#x2019;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 &#x201C;if not&#x201D;. 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&#x2019;s easy to read
The two arrows (>>) is actually a method on the Date object that adds months. So here, we&#x2019;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&#x2019;s no type checking here.
The = is part of the method name. And Ruby&#x2019;s interpreter doesn&#x2019;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&#x2019;s go through adding our &#x201C;on_probation?&#x201D; 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&#x2019;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&#x2019;t need to specify a &#x201C;return&#x201D; 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&#x2019;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&#x2019;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&#x2019;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&#x2019;s a duck. Even if it&#x2019;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&#x2019;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&#x2019;s not a tacked on library, and it&#x2019;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.