39. Error handling
begin
raise "Standard error"
rescue => e
p e
end
# >> #<RuntimeError: Standard error>
begin
raise StandardError.new("Oh, oh")
rescue RuntimeError
puts "runtime"
rescue StandardError
puts "standard"
end
# >> standard
40. System interaction
system "ls"
output = `ls`
ARGV
File.open('test.txt','w') do |file|
file.write("linen")
file.puts("line")
end
File.read('test.txt')
41. Classes
class Calc
attr_accessor :factor
def initialize(factor=2)
@factor = factor
end
def multiply(value)
@factor * value
end
end
calc = Calc.new
calc.multiply 5 # => 10
calc.factor = 3
calc.multiply 5 # => 15
42. Inheritance
class Foo
def greet
"Hi, #{value}"
end
def value
"foo"
end
end
class Bar < Foo
def value
"bar"
end
end
Foo.new.greet # => "Hi, foo"
Bar.new.greet # => "Hi, bar"
43. Mixins & Open Classes
module Even
def even?
self % 2 == 0
end
end
class Fixnum
include Even
end
1.even? # => false
2.even? # => true
44. Class methods
class Foo
def self.bar
"BAR!"
end
def bar
"bar"
end
end
Foo.bar # => "BAR!"
Foo.new.bar # => "bar"
51. Rspec
it "should be awesome" do
foobar = FooBar.new
foobar.should be_awesome
end
52. Cucumber
Feature: Write blog post
As a blogger
I want to create a new blog post
So that I can share my knowledge
Scenario: Click the Add group button
Given I am on the homepage
When I follow "New post"
Then I should be on the new blog post page
Given /^I am on (.+)$/ do |page_name|
visit path_to(page_name)
end
54. DSL: Rake
desc "Clean everything up"
task :cleanup do
Cleaner.cleanup!
end
desc "Make sure everything is shiny"
task :shiny => :cleanup do
Shiner.polish!
end
55. DSL: Capistrano
set :application, "blog"
set :repository, "git@github.com:Narnach/#{application}.git"
set :deploy_to, "/var/www/www.#{application}.com"
set :scm, :git
role :web, "server"
role :app, "server"
role :db, "server", :primary => true
namespace :deploy do
desc "Restart Passenger"
task :restart, :roles => :app, :except => { :no_release => true } do
run "touch #{File.join(current_path,'tmp','restart.txt')}"
end
end