90
Introduction to Ruby & Ruby on Rails Marcelo Correia Pinheiro http://salizzar.net - @salizzar - https://github.com/salizzar Wednesday, October 2, 13

Introduction to Ruby & Ruby on Rails

Embed Size (px)

DESCRIPTION

Slides from my workshop on FCI Academic Week, Mackenzie University - São Paulo.

Citation preview

Page 1: Introduction to Ruby & Ruby on Rails

Introduction to Ruby & Ruby on RailsMarcelo Correia Pinheirohttp://salizzar.net - @salizzar - https://github.com/salizzar

Wednesday, October 2, 13

Page 2: Introduction to Ruby & Ruby on Rails

More one programming language? Maybe, depends on you

Today, knowledge of compiled / bytecoded / interpreted programming languages are requirements in market to programmers that wants to work in *nice real world*

“A language that doesn’t affect the way you think about programming, is not worth knowing.” Perlis, Alan (ALGOL)

wat

Wednesday, October 2, 13

Page 3: Introduction to Ruby & Ruby on Rails

Tell me moreRuby is a general-purpose Object-Oriented Programming language.

But we can consider it as a “hybrid language”, due for their functional-paradigm support

Created by Yukihiro Matsumoto (aka Matz) in Japan, 1995

Heavily inspired on Smalltalk with some flavor of Eiffel, Lisp, Python and others

Current version: 2.0

Wednesday, October 2, 13

Page 4: Introduction to Ruby & Ruby on Rails

Ruby Philosophy

“A programming language for human beings”.

Expressive code

Powerful expansion by Metaprogramming / Functional Paradigm

Make programming more fun

Be productive

Wednesday, October 2, 13

Page 5: Introduction to Ruby & Ruby on Rails

Ruby CommunityOne of most innovative and active today:

Ruby on Rails

TDD / BDD, Configuration Management

A LOT of libraries that inspired other communities (Python, Go, Java, C# etc)

Has created other Virtual Machine implementations (default is MRI):

JRuby (runs on JVM)

Rubinius (written in C++ with LLVM)

Maglev (written in Smalltalk)

RubyMotion (runs on iOS and OSX)

Wednesday, October 2, 13

Page 6: Introduction to Ruby & Ruby on Rails

Who uses RubyOn Planet Earth:

Twitter (meh)

NASA

Google

Groupon

Github

A lot of startups

Wednesday, October 2, 13

Page 7: Introduction to Ruby & Ruby on Rails

Who uses RubyIn HUEland:

Locaweb

Globo.com

UOL

Abril

A lot of startups

Wednesday, October 2, 13

Page 8: Introduction to Ruby & Ruby on Rails

Time to codeIn this keynote, we will see:

IRB (Interactive Ruby Shell)

Flow Control Mechanisms

Ruby Main Classes

Classes, Modules and Mix-ins

Some Ruby STDLIB classes

Ruby Libraries

Wednesday, October 2, 13

Page 9: Introduction to Ruby & Ruby on Rails

IRB (Interactive Ruby Shell)

Many dynamic languages offers a shell for fun and learn, Ruby too

Shipped version is better than otthers REPL shells

Just type in your terminal:

$ irb

Wednesday, October 2, 13

Page 10: Introduction to Ruby & Ruby on Rails

IRB (Interactive Ruby Shell)

Is very nice, but...

Let’s look at pry, an improvement to irb:

$ pry

[1] pry(main)> def hello(fella)[1] pry(main)* puts "Hello, #{fella}! :)"[1] pry(main)* end=> nil[2] pry(main)> hello 'marcelo'Hello, marcelo! :)=> nil

Wednesday, October 2, 13

Page 11: Introduction to Ruby & Ruby on Rails

Flow Control Mechanismsif / else

[1] pry(main)> require 'date'=> true[2] pry(main)> condition = Date.today.sunday?=> true[3] pry(main)> if condition then[3] pry(main)* puts 'condition is true'[3] pry(main)* else[3] pry(main)* puts 'condition is false'[3] pry(main)* endcondition is true=> nil[4] pry(main)> puts 'condition is true' if conditioncondition is true=> nil

Wednesday, October 2, 13

Page 12: Introduction to Ruby & Ruby on Rails

Flow Control Mechanismsunless / else

[1] pry(main)> require 'date'=> true[2] pry(main)> condition = Date.today.monday?=> false[3] pry(main)> unless condition then[3] pry(main)* puts 'condition is false'[3] pry(main)* else[3] pry(main)* puts 'condition is true'[3] pry(main)* endcondition is false=> nil[4] pry(main)> puts 'condition is false' unless conditioncondition is false=> nil

Wednesday, October 2, 13

Page 13: Introduction to Ruby & Ruby on Rails

Flow Control Mechanismswhile

[1] pry(main)> i = 1[2] pry(main)> while i <= 3[2] pry(main)* puts i ; i += 1[2] pry(main)* end123[3] pry(main)> i = 1[4] pry(main)> begin[4] pry(main)* puts i ; i += 1[4] pry(main)* end while i <= 3123

Wednesday, October 2, 13

Page 14: Introduction to Ruby & Ruby on Rails

Flow Control Mechanismsuntil

[1] pry(main)> i = 1[2] pry(main)> until i > 3[2] pry(main)* puts i ; i += 1[2] pry(main)* end123[3] pry(main)> i = 1[4] pry(main)> begin[4] pry(main)* puts i ; i += 1[4] pry(main)* end until i > 3123

Wednesday, October 2, 13

Page 15: Introduction to Ruby & Ruby on Rails

Flow Control Mechanismsfor each

[1] pry(main)> for i in (1..3)[1] pry(main)* puts i[1] pry(main)* end123[2] pry(main)> (1..3).each do |i|[2] pry(main)* puts i[2] pry(main)* end123

Wednesday, October 2, 13

Page 16: Introduction to Ruby & Ruby on Rails

Ruby Main ClassesString

Symbol

Fixnum

Bignum

Range

Float

Date

Time

Array

Hash

Proc

Lambda

Regexp

Wednesday, October 2, 13

Page 17: Introduction to Ruby & Ruby on Rails

Before coding, remember

It’s all about OOP.

Everything is object (strings, numbers etc)

All objects are passed by reference in method calls

Object communicates themselves by message exchange (Smalltalk philosophy)

Wednesday, October 2, 13

Page 18: Introduction to Ruby & Ruby on Rails

Before coding, remember

$ pry

[1] pry(main)> 2 + 2=> 4[2] pry(main)> 2.send(:+, 2)=> 4

Wednesday, October 2, 13

Page 19: Introduction to Ruby & Ruby on Rails

Ruby Main Classes: String

So. Simple. No. Mistery.

As all Ruby Core classes, contains a lot of useful methods for mundane-daily-manipulation

Wednesday, October 2, 13

Page 20: Introduction to Ruby & Ruby on Rails

Ruby Main Classes: String

[1] pry(main)> message = 'Hi, HUEland!'=> "Hi, HUEland!"[2] pry(main)> message.size=> 12[3] pry(main)> message.gsub(/HUEland/, 'Brazil')=> "Hi, Brazil!"[4] pry(main)> message.split(', ')=> ["Hi", "HUEland!"]

Wednesday, October 2, 13

Page 21: Introduction to Ruby & Ruby on Rails

Ruby Main Classes: String

Exercise 01: given a string, loop inside their chars and output respective char and ASCII code

Tip #1: ‘c’.ord returns ASCII code

Tip #2: string[i] returns respective char in string (default index is 0)

Tip #3: to print string, puts string[i].ord

Wednesday, October 2, 13

Page 22: Introduction to Ruby & Ruby on Rails

Ruby Main Classes: Symbol

Symbols are strings that are stored as unique identifiers in memory

In other words, when you create a symbol and uses it in your program, all references to these symbol appoints to same instance while application is running

Wednesday, October 2, 13

Page 23: Introduction to Ruby & Ruby on Rails

Ruby Main Classes: Symbol

[1] pry(main)> symbol = :HUEland=> :HUEland[2] pry(main)> symbol.object_id=> 677228[3] pry(main)> :HUEland.object_id=> 677228

Wednesday, October 2, 13

Page 24: Introduction to Ruby & Ruby on Rails

Ruby Main Classes: Fixnum

Well-known as Integer, but with some differences

Ruby stores numbers in memory based on machine architecture (native machine word - 1 byte)

If a number is insanely big and exceeds upper and lower bounds, is converted to a Bignum automagically

Wednesday, October 2, 13

Page 25: Introduction to Ruby & Ruby on Rails

Ruby Main Classes: Fixnum

[1] pry(main)> universe_answer = 42=> 42[2] pry(main)> universe_answer.chr=> "*"[3] pry(main)> universe_answer.zero?=> false

Wednesday, October 2, 13

Page 26: Introduction to Ruby & Ruby on Rails

Ruby Main Classes: Fixnum

Exercise 02: write a Fibonacci method with recursion

Wednesday, October 2, 13

Page 27: Introduction to Ruby & Ruby on Rails

Ruby Main Classes: Bignum

As name says, a <censored> big number

It’s like Higgs Boson particle on daily programming, nobody has ever seen

Wednesday, October 2, 13

Page 28: Introduction to Ruby & Ruby on Rails

Ruby Main Classes: Bignum

[1] pry(main)> fixnum = 2 ** 62 - 1=> 4611686018427387903[2] pry(main)> fixnum.class=> Fixnum[3] pry(main)> bignum = fixnum + 1=> 4611686018427387904[4] pry(main)> bignum.class=> Bignum

Wednesday, October 2, 13

Page 29: Introduction to Ruby & Ruby on Rails

Ruby Main Classes: Range

Believe me: is a range. (meh)

You don’t need to create arrays of indexes [ 1..5 ] or create famous “i” variables to be used in a while loop, just use (1..5).each

Wednesday, October 2, 13

Page 30: Introduction to Ruby & Ruby on Rails

Ruby Main Classes: Range[1] pry(main)> range = (1..3)=> 1..3[2] pry(main)> range.each { |i| puts i }123=> 1..3[3] pry(main)> range.reverse_each { |i| puts i }321=> 1..3

Wednesday, October 2, 13

Page 31: Introduction to Ruby & Ruby on Rails

Ruby Main Classes: RangeExercise 03: From 1 to 100, print number and if is prime

Tip: use the following method

If is strange, don’t worry; you will understand it soon :)

def prime?(x) (2 .. Math.sqrt(x)).each { |n| return false if x % n == 0 } trueend

Wednesday, October 2, 13

Page 32: Introduction to Ruby & Ruby on Rails

Ruby Main Classes: Float

A float (O’RLY?)

As all Ruby classes, contains some interesting methods (RTFM)

Wednesday, October 2, 13

Page 33: Introduction to Ruby & Ruby on Rails

Ruby Main Classes: Float

[1] pry(main)> pi = Math::PI=> 3.141592653589793[2] pry(main)> pi.ceil=> 4[3] pry(main)> pi.floor=> 3[4] pry(main)> pi.denominator=> 281474976710656[5] pry(main)> pi.modulo(1)=> 0.14159265358979312

Wednesday, October 2, 13

Page 34: Introduction to Ruby & Ruby on Rails

Ruby Main Classes: Date

Meh.

Support for Julian Calendar and other RFC methods

Support arithmetical operations with integers and other types

Wednesday, October 2, 13

Page 35: Introduction to Ruby & Ruby on Rails

Ruby Main Classes: Date[1] pry(main)> require 'date'=> true[2] pry(main)> today = Date.today=> #<Date: 2013-09-21 ((2456557j,0s,0n),+0s,2299161j)>[3] pry(main)> today.day=> 21[4] pry(main)> today.month=> 9[5] pry(main)> today.year=> 2013[6] pry(main)> today.sunday?=> true[6] pry(main)> today - 4=> #<Date: 2013-09-27 ((2456553j,0s,0n),+0s,2299161j)>

Wednesday, October 2, 13

Page 36: Introduction to Ruby & Ruby on Rails

Ruby Main Classes: Time

Date with time (hour, minutes and seconds)

IMPORTANT: Ruby have two Time implementations:

A class from Core, that have a lot of methods

A module from STDLIB that contains parsing feature and other methods

Wednesday, October 2, 13

Page 37: Introduction to Ruby & Ruby on Rails

Ruby Main Classes: Time

1] pry(main)> now = Time.now=> 2013-09-21 13:35:24 -0300[2] pry(main)> require 'time'=> true[3] pry(main)> now = Time.parse "#{Date.today} #{Time.now.strftime "%H:%M:%S"}"=> 2013-09-21 13:36:13 -0300

Wednesday, October 2, 13

Page 38: Introduction to Ruby & Ruby on Rails

Ruby Main Classes: Array

Meh.

A LOT of useful methods like select, collect, reverse, sort and others

Accepts anything (numbers, strings, constants etc)

Wednesday, October 2, 13

Page 39: Introduction to Ruby & Ruby on Rails

Ruby Main Classes: Array

[1] pry(main)> primes = [ 1, 2, 3, 5, 7, 11 ]=> [1, 2, 3, 5, 7, 11][2] pry(main)> pingu_speaking = %w(emmgpiqncqa cefpgqiqmeuolg pxregmeuyytg)=> ["emmgpiqncqa", "cefpgqiqmeuolg", "pxregmeuyytg"][3] pry(main)> moms_heart = [ :one, 2, 'three', Float ]=> [:one, 2, 'three', Float][4] pry(main)> primes.select(&:odd?)=> [1, 3, 5, 7, 11][5] pry(main)> moms_heart.reject { |item| item.is_a?(Symbol) }=> [2, "three", Float]

Wednesday, October 2, 13

Page 40: Introduction to Ruby & Ruby on Rails

Ruby Main Classes: Array

Exercise 04: From 1 to 100, store prime numbers in a array

Tip: use previous exercise to help

Wednesday, October 2, 13

Page 41: Introduction to Ruby & Ruby on Rails

Ruby Main Classes: Hash

A dictionary (O’RLY?)

Shares same behavior of Array, accepts anything as keys/values

You can do some fun routines with it

Wednesday, October 2, 13

Page 42: Introduction to Ruby & Ruby on Rails

Ruby Main Classes: Hash[1] pry(main)> moms_heart = { 1 => :one, :two => 2, 3.0 => 'three' }=> {1=>:one, :two=>2, 3.0=>"three"}[2] pry(main)> moms_heart[3.0]=> "three"[3] pry(main)> moms_heart.keys=> [1, :two, 3.0][4] pry(main)> moms_heart.values=> [:one, 2, "three"][5] pry(main)> moms_heart['daddy']=> nil[6] pry(main)> moms_heart[:float] = Float=> Float[7] pry(main)> moms_heart[:float]=> Float

Wednesday, October 2, 13

Page 43: Introduction to Ruby & Ruby on Rails

Ruby Main Classes: Hash

Exercise 05: From 1 to 100, stores in a hash the last digit of a prime number as a key and value inside a array

Wednesday, October 2, 13

Page 44: Introduction to Ruby & Ruby on Rails

Ruby Main Classes: ProcTime to get real fun.

Ruby is a hybrid language, right? YES

Let’s talk about some Computation Theory

First-class citizens

Anonymous functions

Closures & Blocks

Wednesday, October 2, 13

Page 45: Introduction to Ruby & Ruby on Rails

Ruby Main Classes: Proc

In Ruby, as documentation says:

“Proc objects are blocks of code that have been bound to a set of local variables. Once bound, the code may be called in different contexts and still access those variables.”

Wednesday, October 2, 13

Page 46: Introduction to Ruby & Ruby on Rails

Ruby Main Classes: Proc[1] pry(main)> def get_factor(factor)[1] pry(main)* Proc.new { |n| factor ** n }[1] pry(main)* end=> nil[2] pry(main)> factor_of_2 = get_factor(2)=> #<Proc:0x000000014cec48@(pry):2>[3] pry(main)> factor_of_2.call(5)=> 32[4] pry(main)> factor_of_3 = get_factor(3)=> #<Proc:0x0000000135df30@(pry):2>[5] pry(main)> factor_of_3.call(4)=> 81

Wednesday, October 2, 13

Page 47: Introduction to Ruby & Ruby on Rails

Ruby Main Classes: Lambda

Lambda is a Proc, with *important* differences

A lambda checks arity of arguments passed

return keyword behaves differently compared to Proc instances

Wednesday, October 2, 13

Page 48: Introduction to Ruby & Ruby on Rails

Ruby Main Classes: Lambda[1] pry(main)> def get_a_lambda(fella)[1] pry(main)* ret = lambda { return "Lambda hello, #{fella}" }[1] pry(main)* ret.call[1] pry(main)* "#{fella}, you will see this message"[1] pry(main)* end=> nil[2] pry(main)> def get_a_proc(fella)[2] pry(main)* ret = Proc.new { return "Proc hello, #{fella}" }[2] pry(main)* ret.call[2] pry(main)* "#{fella}, you will never see this message"[2] pry(main)* end=> nil[3] pry(main)> get_a_lambda('Marcelo')=> "Marcelo, you will see this message"[4] pry(main)> get_a_proc('Marcelo')=> "Proc hello, Marcelo"

Wednesday, October 2, 13

Page 49: Introduction to Ruby & Ruby on Rails

Ruby Main Classes: Lambda

Exercise 06: rewrite Fibonacci method as a lambda

Wednesday, October 2, 13

Page 50: Introduction to Ruby & Ruby on Rails

Ruby Main Classes: Regexp

Regular Expressions (O’RLY?)

If you never heard about it... don’t worry, the day that you need to extract some text patterns in log files will come

Wednesday, October 2, 13

Page 51: Introduction to Ruby & Ruby on Rails

Ruby Main Classes: Regexp

[1] pry(main)> message = "Gooby pls xow em de code"=> "Gooby pls xow em de code"[2] pry(main)> a_pattern = /gooby/i=> /gooby/i[3] pry(main)> another = Regexp.new('pls xow em de code')=> /xow em de code/[4] pry(main)> message.gsub(a_pattern, 'Dolan').gsub(another, 'you shall not pass')=> "Dolan you shall not pass"

Wednesday, October 2, 13

Page 52: Introduction to Ruby & Ruby on Rails

Ruby Main Classes: Regexp

You know how use it, let’s gonna exercise with a LIVE example replacing all occurrences of aeiou with *

Wednesday, October 2, 13

Page 53: Introduction to Ruby & Ruby on Rails

Ruby Classes

OK, Ruby seems to be cool. How I start to create some classes?

Let’s revisit inheritance and polymorphism.

Ruby have public, protected and private accessors

Ruby not have abstract classes and interfaces

Ruby not supports multiple inheritance, but with Modules we can provide it (Mix-ins)

Wednesday, October 2, 13

Page 54: Introduction to Ruby & Ruby on Rails

Ruby Classes

[1] pry(main)> class GeometricShape[1] pry(main)* def get_area[1] pry(main)* raise NotImplementedError.new[1] pry(main)* end[1] pry(main)* end=> nil[2] pry(main)> wat = GeometricShape.new=> #<GeometricShape:0x0000000257dc10>[3] pry(main)> wat.get_areaNotImplementedError: NotImplementedErrorfrom (pry):3:in `get_area'

Wednesday, October 2, 13

Page 55: Introduction to Ruby & Ruby on Rails

Ruby Classes[4] pry(main)> class Square < GeometricShape[4] pry(main)* attr_accessor :length[4] pry(main)*[4] pry(main)* def get_area[4] pry(main)* @length ** 2[4] pry(main)* end[4] pry(main)* end=> nil[5] pry(main)> square = Square.new=> #<Square:0x000000024326f8>[6] pry(main)> square.length = 4=> 4[7] pry(main)> square.get_area=> 16

Wednesday, October 2, 13

Page 56: Introduction to Ruby & Ruby on Rails

Ruby Classes[8] pry(main)> class Triangle < GeometricShape[8] pry(main)* attr_accessor :base, :height[8] pry(main)*[8] pry(main)* def get_area[8] pry(main)* (base * height) / 2[8] pry(main)* end[8] pry(main)* end=> nil[9] pry(main)> triangle = Triangle.new=> #<Triangle:0x000000026b7248>[10] pry(main)> triangle.base = 4 ; triangle.height = 5=> 5[11] pry(main)> triangle.get_area=> 10

Wednesday, October 2, 13

Page 57: Introduction to Ruby & Ruby on Rails

Ruby Classes

Exercise 07: create a Trapezium class that extends GeometricShape and write get_area method

Wednesday, October 2, 13

Page 58: Introduction to Ruby & Ruby on Rails

Ruby Modules / Mix-insModules are a fragment of code (methods, other classes, constants etc) that we can include:

In classes

In other modules

We use to create namespaces too

In Ruby, we call action of including a Module inside a class / other module as Mix-in

Wednesday, October 2, 13

Page 59: Introduction to Ruby & Ruby on Rails

Ruby Modules / Mix-ins[1] pry(main)> module GUI[1] pry(main)* module Renderer[1] pry(main)* def render[1] pry(main)* "Rendering #{self.class.name} with Area #{self.get_area}... done"[1] pry(main)* end[1] pry(main)* end[1] pry(main)* end=> nil[2] pry(main)> class Square[2] pry(main)* include GUI::Renderer[2] pry(main)* end=> Square[3] pry(main)> class Triangle[3] pry(main)* include GUI::Renderer[3] pry(main)* end=> Triangle

Wednesday, October 2, 13

Page 60: Introduction to Ruby & Ruby on Rails

Ruby Modules / Mix-ins

[4] pry(main)> square = Square.new=> #<Square:0x00000000e85c88>[5] pry(main)> square.length = 3=> 3[6] pry(main)> square.render=> "Rendering Square with Area 9... done"[7] pry(main)> triangle = Triangle.new=> #<Triangle:0x00000000f5f398>[8] pry(main)> triagle.base = 3 ; triagle.height = 4=> 4[9] pry(main)> triangle.render=> "Rendering Triangle with Area 6... done"

Wednesday, October 2, 13

Page 61: Introduction to Ruby & Ruby on Rails

Ruby STDLIB ClassesRuby provides *a lot* of useful classes

Check ruby-doc.org before starting to code, maybe it is shipped :)

We will see the following:

Net::HTTP

Benchmark

Test::Unit

Wednesday, October 2, 13

Page 62: Introduction to Ruby & Ruby on Rails

Ruby STDLIB Classes: Net::HTTP

A HTTP client to GET, POST, PUT and DELETE

HTTPS Support

Interface not so good, but community has created other libraries that encapsulates calls in a better way

Wednesday, October 2, 13

Page 63: Introduction to Ruby & Ruby on Rails

Ruby STDLIB Classes: Net::HTTP[1] pry(main)> require 'net/http'=> true[2] pry(main)> response = Net::HTTP.get(URI('http://www.terra.com.br'))=> "<!DOCTYPE HTML PUBLIC \"-//IETF//DTD HTML 2.0//EN\">\n<html><head>\n<title>301 Moved Permanently</title>\n</head><body>\n<h1>Moved Permanently</h1>\n<p>The document has moved <a href=\"/portal/\">here</a>.</p>\n</body></html>\n"[3] pry(main)> hash = {}=> {}[4] pry(main)> response.chars.each do |c|[4] pry(main)* hash[c.to_s] = hash[c.to_s].nil? ? 1 : hash[c.to_s] + 1[4] pry(main)* end=> "<!DOCTYPE HTML PUBLIC \"-//IETF//DTD HTML 2.0//EN\">\n<html><head>\n<title>301 Moved Permanently</title>\n</head><body>\n<h1>Moved Permanently</h1>\n<p>The document has moved <a href=\"/portal/\">here</a>.</p>\n</body></html>\n"[5] pry(main)> hash.keys.sort.each do |k|[5] pry(main)* puts "'#{k}' = #{hash[k]}"[5] pry(main)* end=> (... a big input here ...)

Wednesday, October 2, 13

Page 64: Introduction to Ruby & Ruby on Rails

Ruby STDLIB Classes: Net::HTTP

Exercise 08: stores in a Hash all occurrences of chars given a URL that is called using Net::HTTP

Wednesday, October 2, 13

Page 65: Introduction to Ruby & Ruby on Rails

Ruby STDLIB Classes: Benchmark

Benchmark provides a way to measure your code based on elapsed execution time

A need-to-know to check algorithm efficiency

Wednesday, October 2, 13

Page 66: Introduction to Ruby & Ruby on Rails

Ruby STDLIB Classes: Benchmark[1] pry(main)> def fibonacci(x)[1] pry(main)* return x if [ 0, 1 ].include?(x)[1] pry(main)* fibonacci(x - 1) + fibonacci(x - 2)[1] pry(main)* end=> nil[2] pry(main)> fib = lambda do |x|[2] pry(main)* return x if [ 0, 1 ].include?(x)[2] pry(main)* fib[x - 1] + fib[x - 2][2] pry(main)* end=> #<Proc:0x000000029ec710@(pry):14 (lambda)>[3] pry(main)> fibh = lambda do |x|[3] pry(main)* return x if [ 0, 1 ].include?(x)[3] pry(main)* Hash.new { |hash, n| hash[n] = n < 2 ? n : hash[n - 1] + hash[n - 2] }[x][3] pry(main)* end=> #<Proc:0x000000031217d8@(pry):18 (lambda)>

Wednesday, October 2, 13

Page 67: Introduction to Ruby & Ruby on Rails

Ruby STDLIB Classes: Benchmark

[4] pry(main)> require 'benchmark'=> true[5] pry(main)> Benchmark.bm(15) do |b|[5] pry(main)* b.report('fibonacci') { fibonacci(32) }[5] pry(main)* b.report('fib') { fib.call(32) }[5] pry(main)* b.report('fibh') { fibh.call(32) }[5] pry(main)* end user system total realfibonacci 1.890000 0.000000 1.890000 ( 1.888704)fib 2.700000 0.000000 2.700000 ( 2.697208)fibh 0.000000 0.000000 0.000000 ( 0.000056)

Wednesday, October 2, 13

Page 68: Introduction to Ruby & Ruby on Rails

Ruby STDLIB Classes: Test::UnitTest. Your. Code.

If you never heard before about this, seriously... LEARN.

Helps to create better software

No fear while refactoring

Check possible problems in future

Increases application design over time

Wednesday, October 2, 13

Page 69: Introduction to Ruby & Ruby on Rails

Ruby STDLIB Classes: Test::Unit

# 01_fibonacci.rb

def fibonacci(x) return x if x == 0 || x == 1

fibonacci(x - 1) + fibonacci(x - 2)end

Wednesday, October 2, 13

Page 70: Introduction to Ruby & Ruby on Rails

Ruby STDLIB Classes: Test::Unit

require './01_fibonacci'require 'test/unit'

class TestFibonacci < Test::Unit::TestCase def test_fib assert_equal(fibonacci(0), 0) assert_equal(fibonacci(1), 1) assert_equal(fibonacci(10), 55) endend

Wednesday, October 2, 13

Page 71: Introduction to Ruby & Ruby on Rails

Ruby STDLIB Classes: Test::Unit

$ ruby 11_test_hash.rbRun options:

# Running tests:

.

Finished tests in 0.000379s, 2641.7287 tests/s, 7925.1862 assertions/s.

1 tests, 3 assertions, 0 failures, 0 errors, 0 skips

Wednesday, October 2, 13

Page 72: Introduction to Ruby & Ruby on Rails

Ruby STDLIB Classes: Test::Unit

For given exercises, write test FIRST :)

Exercise 09: write a TestCase for 2 + 2

Exercise 10: write a TestCase that asserts that our prime method is correct for 4 scenarios

Tip: use assert_equal

Wednesday, October 2, 13

Page 73: Introduction to Ruby & Ruby on Rails

Ruby LibrariesA Ruby Library is called a Gem.

Ruby community has created a canonical repository: Rubygems.org

Create a library is easy, anyone can create and share in repo; but:

Cover with tests first;

Make it more generic as possible;

NO MONKEY PATCHES* (until you know what you do)

Wednesday, October 2, 13

Page 74: Introduction to Ruby & Ruby on Rails

Ruby LibrariesRuby have a tool to map dependencies and install/vendorize gems: bundler

It requires a Gemfile, a file that we add all required gems to application work

Great advantage: we can ship a Ruby app with all dependencies inside it

Of course, if we use native gems then the destination must have the same OS & architecture (x86, x86_64)

Wednesday, October 2, 13

Page 75: Introduction to Ruby & Ruby on Rails

Ruby Libraries

Time to show how create a Ruby application from zero using bundler.

Wednesday, October 2, 13

Page 76: Introduction to Ruby & Ruby on Rails

Ruby on RailsA little introduction

Wednesday, October 2, 13

Page 77: Introduction to Ruby & Ruby on Rails

Ruby on Rails: wat

A framework to create web applications.

Created by David Heinemeier Hansson (aka @dhh), Denmark 2004

David was attended in FISL 2005 as a speaker to show RoR

Apple was shipped RoR in 2007 in OSX Leopard

Wednesday, October 2, 13

Page 78: Introduction to Ruby & Ruby on Rails

Ruby on Rails: !hypeWhy Rails is so important?

RoR was the first web framework that effectively works well

Microsoft tried to resolve with first version of Microsoft.NET ASP.NET, but create a state persistence in a stateless protocol (HTTP) was failed as hell (ASPNET hidden fields storing >= 128Kb *zipped* strings)

Apache Struts works, but be ready to immerse in dozens of XML configuration files to create a simple Hello World

Wednesday, October 2, 13

Page 79: Introduction to Ruby & Ruby on Rails

Ruby on Rails: Follow my rules

Ruby on Rails is a great example of opinionated software.

Convention over Configuration

Principle of Least Astonishment

KISS (Keep It Simple, Stupid)

DRY (Don’t Repeat Yourself)

Wednesday, October 2, 13

Page 80: Introduction to Ruby & Ruby on Rails

Ruby on Rails: Architecture

Rails is a MVC (Model-View-Controller) framework.

Model: main business rules and persistence

View: presentation layer of data

Controller: a bridge between models and views, based on actions

Wednesday, October 2, 13

Page 81: Introduction to Ruby & Ruby on Rails

Ruby on Rails: Models

Models are classes that maps entities in a database

Models uses ActiveRecord pattern to perform CRUD (Create / Read / Update / Destroy) operations

Rails provides a agnostic interface to query in database with your models

In other words, you don’t need to write SQL commands

Wednesday, October 2, 13

Page 82: Introduction to Ruby & Ruby on Rails

Ruby on Rails: ModelsRails have support for principal RDBMS’s on market

MySQL, PostgreSQL

Microsoft SQL Server, Oracle Database

Rails supports NoSQL Databases very, very well:

CouchDB, MongoDB

Cassandra, Redis

Wednesday, October 2, 13

Page 83: Introduction to Ruby & Ruby on Rails

Ruby on Rails: ModelsModels contains a set of useful validations

Numeric

Regular Expression

Inclusion

Value is blank

etc

Wednesday, October 2, 13

Page 84: Introduction to Ruby & Ruby on Rails

Ruby on Rails: Views

Views are the presentation layer of data.

In Rails, views are fragments of HTML code that will be parsed / executed by the render engine to stream pure HTML to client

Default render engine: ERB

But you can choice others:

Markdown, HAML

Wednesday, October 2, 13

Page 85: Introduction to Ruby & Ruby on Rails

Ruby on Rails: Controllers

Controllers are the man-in-the-middle of Models and Views.

Responsible to receive view data (HTML forms sent by POST/PUT/DELETE) and create Model instances, orchestrate application logic

They *must* be little (tiny controllers, tiny models)

Are a entity that responds to a route

Wednesday, October 2, 13

Page 86: Introduction to Ruby & Ruby on Rails

Ruby on Rails: RoutesTo talk about routes, we must revisit or know what is REST.

An approach to handle resources based on HTTP verbs in WWW

GET /resource -> READ

POST /resource -> CREATE

PUT /resource -> UPDATE

DELETE /resource -> DELETE

We can talk per hours here, but learn by yourself. It is a requirement today.

Wednesday, October 2, 13

Page 87: Introduction to Ruby & Ruby on Rails

Ruby on Rails: Migrations

When we need to create a entity in database, commonly a SQL script is written to a DBA run it in a server.

With Migrations, we can create it without write any SQL script

Previous migrations are stored in database in order to avoid multiple executions (ex: run a CREATE TABLE of a already existent table)

Wednesday, October 2, 13

Page 88: Introduction to Ruby & Ruby on Rails

Ruby on Rails: It’s showtime

Let’s try to create a blog engine (OH NO, AGAIN!)

Wednesday, October 2, 13

Page 89: Introduction to Ruby & Ruby on Rails

Questions?

Gooby pls sk ot me

Wednesday, October 2, 13

Page 90: Introduction to Ruby & Ruby on Rails

Thank you!Solved exercises on:https://github.com/salizzar/introduction-to-ruby

Wednesday, October 2, 13