ruby and the tools topics ruby rails january 15, 2014 csce 740 software engineering
TRANSCRIPT
Ruby and the tools
Ruby and the tools
TopicsTopics Ruby Rails
January 15, 2014
CSCE 740 Software Engineering
– 2 – CSCE 740 Spring 2014
RubyRuby
http://www.ruby-doc.org/
http://ruby.about.com/od/tutorialsontheweb/tp/10waysfree.htm
https://www.ruby-lang.org/en/documentation/quickstart/
Rails and BeyondRails and Beyond
http://ruby.railstutorial.org/ruby-on-rails-tutorial-bookhttp://ruby.railstutorial.org/ruby-on-rails-tutorial-book
– 3 – CSCE 740 Spring 2014
The Rspec Book 2010The Rspec Book 2010
Latest versionsLatest versions
•rubyruby
•ruby-gemsruby-gems
•rspecrspec
•rspec-railsrspec-rails
•cucumbercucumber
•cucumber-railscucumber-rails
•database_cleanerdatabase_cleaner
•webratwebrat
•seleniumselenium
•railsrails
– 4 – CSCE 740 Spring 2014
Read Chapters 1-3 Ruby3Read Chapters 1-3 Ruby3
• http://www.ruby-doc.org/http://www.ruby-doc.org/
Programming Ruby 1.9 Dave Thomas
– 5 – CSCE 740 Spring 2014
Java Ruby - Three Pillars of RubyJava Ruby - Three Pillars of Ruby
1.1. Everything is an object. Everything is an object. in Java an integer needs to be boxed to act like an object.
2.2. Every operation is a method call on some object and Every operation is a method call on some object and returns a value.returns a value.
in Java operator overloading is different from method overriding
3.3. All programming is metaprogramming.All programming is metaprogramming. classes can be added or changed at any time even run time
SaaS book – Fox and Patterson
– 6 – CSCE 740 Spring 2014
Getting StartedGetting Started
ruby –vruby –v
ruby prog.rb ruby prog.rb // puts “hello world\n”// puts “hello world\n”
irbirb // interactive ruby // interactive ruby
http://pragprog.com/titles/ruby3/source_code
ri ClassNameri ClassName //documentation of //documentation of ClassNameClassName
Programming Ruby 1.9 Dave Thomas
– 7 – CSCE 740 Spring 2014
Ruby is Really Object Oriented Ruby is Really Object Oriented Really Object Oriented – everything is an objectReally Object Oriented – everything is an object
For Java you might use
pos = Math.abs(num) In Ruby
num = -123
pos = num.abs
Variables inside literal strings #{ … } notationVariables inside literal strings #{ … } notation puts “the absolute value of #{num} is #{pos}\n”
Prog Ruby 1.9 Dave Thomas
– 8 – CSCE 740 Spring 2014
Ruby - Variable Name ConventionsRuby - Variable Name Conventions Variable Name PunctuationVariable Name Punctuation
name - local variablename - local variable
$name, $NAME, - globals (never use anyway!)$name, $NAME, - globals (never use anyway!)
@name – instance variables@name – instance variables
@@name – class variables@@name – class variables
Name – class names and constantsName – class names and constants
Prog Ruby 1.9 Dave Thomas
– 9 – CSCE 740 Spring 2014
Puts_examplesPuts_examples
song = 1song = 1
sam = ""sam = ""
def sam.play(a)def sam.play(a)
"duh dum, da dum de dum ...""duh dum, da dum de dum ..."
endend
puts "gin joint".lengthputs "gin joint".length
puts "Rick".index("c")puts "Rick".index("c")
puts 42.even?puts 42.even?
puts sam.play(song)puts sam.play(song)
print “string with no newline”print “string with no newline”Programming Ruby 1.9 Dave Thomas
– 10 – CSCE 740 Spring 2014
SymbolsSymbols
:rhubarb - is an immutable string whose value is value :rhubarb - is an immutable string whose value is value is itself, well without the colonis itself, well without the colon
:rhubarb.to_s yields “rhubarb”:rhubarb.to_s yields “rhubarb”
““rhubarb”.to_sym yields :rhubarb rhubarb”.to_sym yields :rhubarb
not a string – string operations cannot be performed on not a string – string operations cannot be performed on itit
– 11 – CSCE 740 Spring 2014
Method definitionMethod definition
def say_goodnight(name)def say_goodnight(name)
result = "Good night, " + nameresult = "Good night, " + name
return resultreturn result
endend
# Time for bed...# Time for bed...
puts say_goodnight("John-Boy")puts say_goodnight("John-Boy")
puts say_goodnight("Mary-Ellen")puts say_goodnight("Mary-Ellen")
Programming Ruby 1.9 Dave Thomas
– 12 – CSCE 740 Spring 2014
CSE Linux Labs CSE Linux Labs
• 1D39 – Combination on secure site1D39 – Combination on secure site• CSE home page – login with CEC credentials• Computer resources/Computer labs
• List of Linux workstationsList of Linux workstations• IP addresses – machine names
• Ifconfig // interface config IPv4 addr and Ifconfig // interface config IPv4 addr and Hardware=ethernet addrHardware=ethernet addr
• ““man keyword” online unix documentationman keyword” online unix documentation
– 13 – CSCE 740 Spring 2014
Figure 3.1 Basic Ruby ElementsFigure 3.1 Basic Ruby Elements
SaaS book – Fox and Patterson
– 14 – CSCE 740 Spring 2014
List of Ruby 3 ExamplesList of Ruby 3 Examples
1.1. Getting Started – “hello, Ruby Programmer”Getting Started – “hello, Ruby Programmer”
2.2. Intro – Intro – a. Hello1 – def say_goodnight
b. Puts examples
c. Cmd_line – command line args passed into ruby program
d. “arrays” – non-homogeneous
e. hash_with_symbol_keys_19.rb –
f. Weekdays – control structures – if-elseif-else example
3.3. Tutclasses-Tutclasses-
– 15 – CSCE 740 Spring 2014
google(ruby 1.9 tutorial)google(ruby 1.9 tutorial)
• Ruby Programming Language - - ruby-lang.org/ ruby-lang.org/
• http://www.ruby-doc.org/ (again) (again)
• http://pragprog.com/titles/ruby3/source_code http://pragprog.com/titles/ruby3/source_code (again)(again)
• http://pragprog.com/book/ruby3/programming-ruby-http://pragprog.com/book/ruby3/programming-ruby-1-9 “Buy the book” page1-9 “Buy the book” page• Regular Expressions (download pdf)• Namespaces, Source Files, and Distribution (download pdf)• Ruby Library Reference
• Built-in Classes and Modules (download pdf of the entry for class Array)
• Standard Library
• http://www.ruby-doc.org/stdlib-1.9.3/ http://www.ruby-doc.org/stdlib-1.9.3/
– 16 – CSCE 740 Spring 2014
Arrays and HashesArrays and Hashes
http://ruby-doc.org/docs/ProgrammingRuby/
a = [ 1, 'cat', 3.14 ] # array with three elements
# access the first element
a[0] » 1
# set the third element
a[2] = nil
# dump out the array
a » [1, "cat", nil]
– 17 – CSCE 740 Spring 2014
Control Structures IFControl Structures IF
if count > 10 if count > 10 // body// body
puts "Try again" puts "Try again"
elsif tries == 3 elsif tries == 3
puts "You lose" puts "You lose"
else else
puts "Enter a number" puts "Enter a number"
endend
http://ruby-doc.org/docs/ProgrammingRuby/
– 18 – CSCE 740 Spring 2014
Control Structures WhileControl Structures While
while weight < 100 and numPallets <= 30 while weight < 100 and numPallets <= 30
pallet = nextPallet() pallet = nextPallet()
weight += pallet.weight weight += pallet.weight
numPallets += 1numPallets += 1
endend
http://ruby-doc.org/docs/ProgrammingRuby/
– 19 – CSCE 740 Spring 2014
More controlMore control
puts "Danger, Will Robinson" if radiation > 3000puts "Danger, Will Robinson" if radiation > 3000
while square < 1000 while square < 1000
square = square*square square = square*square
endend
More concisely, but readability??More concisely, but readability??
square = square*square while square < 1000square = square*square while square < 1000
http://ruby-doc.org/docs/ProgrammingRuby/
– 20 – CSCE 740 Spring 2014
Regular ExpressionsRegular Expressions
Regular expressions are expressions that specify Regular expressions are expressions that specify collections of strings (formally languages)collections of strings (formally languages)
Main operators: Assume r and s are regular expressions Main operators: Assume r and s are regular expressions then so are:then so are:
r | sr | s alternation denotes L(r) U L(s)alternation denotes L(r) U L(s)
rsrs concatenation which denotes L(r) L(s)concatenation which denotes L(r) L(s)
r*r* Kleene closure zero or more occurrences of Kleene closure zero or more occurrences of strings from L(r) concatenatedstrings from L(r) concatenated
Base regular expressionsBase regular expressions
•strings are regexpr that match themselves,L(“ab”) = {“ab”}strings are regexpr that match themselves,L(“ab”) = {“ab”}
•the empty string the empty string εε is a regular expr L( is a regular expr L(εε) = {“”}) = {“”}
– 21 – CSCE 740 Spring 2014
Regular Expressions ExamplesRegular Expressions Examples
• ??
– 22 – CSCE 740 Spring 2014
Ruby Regular Expressions ExamplesRuby Regular Expressions Examples
– 23 – CSCE 740 Spring 2014
Ruby Regular ExpressionsRuby Regular Expressions
if line =~ /Perl|Python/ if line =~ /Perl|Python/
puts "Scripting language mentioned: #{line}”puts "Scripting language mentioned: #{line}”
endend
line.sub(/Perl/, 'Ruby') # replace first 'Perl' with 'Ruby' line.sub(/Perl/, 'Ruby') # replace first 'Perl' with 'Ruby' line.gsub(/Python/, 'Ruby') # line.gsub(/Python/, 'Ruby') # replace every 'Python' with 'Ruby' replace every 'Python' with 'Ruby'
http://ruby-doc.org/docs/ProgrammingRuby/
– 24 – CSCE 740 Spring 2014
BlocksBlocks
a = %w( ant bee cat dog elk ) # create an array a = %w( ant bee cat dog elk ) # create an array
a.each { |animal| puts animal } # iterate over the contentsa.each { |animal| puts animal } # iterate over the contents
Yield – will be discussed next timeYield – will be discussed next time
[ 'cat', 'dog', 'horse' ].each do |animal| [ 'cat', 'dog', 'horse' ].each do |animal|
print animal, " -- "print animal, " -- "
http://ruby-doc.org/docs/ProgrammingRuby/
– 25 – CSCE 740 Spring 2014
BlocksBlocks
5.times { print "*" } 5.times { print "*" }
3.upto(6) {|i| print i } 3.upto(6) {|i| print i }
('a'..'e').each {|char| print char }('a'..'e').each {|char| print char }
*****3456abcde*****3456abcde
http://ruby-doc.org/docs/ProgrammingRuby/
– 26 – CSCE 740 Spring 2014
Ruby I/ORuby I/O
• Already seenAlready seen• puts• print • P
• On readingOn reading• Gets• Iterate over lines of file
– 27 – CSCE 740 Spring 2014
while gets while gets # assigns line to $_ # assigns line to $_
if /Ruby/ if /Ruby/ # matches against $_ # matches against $_
print print # prints $_ # prints $_
end end
endend
ARGF.each { |line| print line if line =~ /Ruby/ }ARGF.each { |line| print line if line =~ /Ruby/ }
http://ruby-doc.org/docs/ProgrammingRuby/
– 28 – CSCE 740 Spring 2014
Classes, Objects etc.Classes, Objects etc.
class Song class Song
def initialize(name, artist, duration) def initialize(name, artist, duration)
@name = name @name = name
@artist = artist @artist = artist
@duration = duration @duration = duration
endend
endend
s0 =Song.news0 =Song.new
http://ruby-doc.org/docs/ProgrammingRuby/
– 29 – CSCE 740 Spring 2014
aSong = Song.new("Bicylops", "Fleck", 260)aSong = Song.new("Bicylops", "Fleck", 260)
aSong.inspectaSong.inspect
aSong.to_saSong.to_s
http://ruby-doc.org/docs/ProgrammingRuby/
– 30 – CSCE 740 Spring 2014
InheritanceInheritance
class KaraokeSong < Song class KaraokeSong < Song
def initialize(name, artist, duration, lyrics) def initialize(name, artist, duration, lyrics)
super(name, artist, duration) super(name, artist, duration)
@lyrics = lyrics @lyrics = lyrics
endend
EndEnd
aSong = KaraokeSong.new("My Way", "Sinatra", 225, "aSong = KaraokeSong.new("My Way", "Sinatra", 225, "And now, the...")And now, the...")
aSong.to_saSong.to_s
http://ruby-doc.org/docs/ProgrammingRuby/
– 31 – CSCE 740 Spring 2014
Accessing instance variablesAccessing instance variables
http://ruby-doc.org/docs/ProgrammingRuby/
class Song
def name
@name
end
def artist
@artist
end
def duration
@duration
end
end
– 32 – CSCE 740 Spring 2014
Class SongClass Song
attr_reader :name, :artist, :durationattr_reader :name, :artist, :duration
……
end end
http://ruby-doc.org/docs/ProgrammingRuby/
– 33 – CSCE 740 Spring 2014
class JavaSong { // Java code class JavaSong { // Java code
private Duration myDuration; private Duration myDuration;
public void setDuration(Duration newDuration) {public void setDuration(Duration newDuration) {
myDuration = newDuration; myDuration = newDuration;
} }
}}
class Song class Song
attr_writer :duration attr_writer :duration
endend
http://ruby-doc.org/docs/ProgrammingRuby/
– 34 – CSCE 740 Spring 2014
class Song class Song @@plays = 0 @@plays = 0 def initialize(name, artist, duration) def initialize(name, artist, duration)
@name = name @name = name @artist = artist @artist = artist @duration = duration @duration = duration @plays = 0 @plays = 0
end end def play def play
@plays += 1 @plays += 1 @@plays += 1 @@plays += 1
"song: #@plays plays. Total #@@plays plays." "song: #@plays plays. Total #@@plays plays." endend
http://ruby-doc.org/docs/ProgrammingRuby/
– 35 – CSCE 740 Spring 2014
Class MethodsClass Methods
class Example class Example
def instMeth def instMeth # instance method # instance method
……
end end
def Example.classMeth def Example.classMeth # class method # class method
……
end end
endend
http://ruby-doc.org/docs/ProgrammingRuby/
– 36 – CSCE 740 Spring 2014
SingletonsSingletons
class Logger class Logger
private_class_method :new private_class_method :new
@@logger = nil @@logger = nil
def Logger.create def Logger.create
@@logger = new unless @@logger @@logger = new unless @@logger
@@logger @@logger
end end
endend
http://ruby-doc.org/docs/ProgrammingRuby/
Logger.create.id » 537766930 Logger.create.id » 537766930
– 37 – CSCE 740 Spring 2014
Access Control Access Control
““Public methods can be called by anyone---there is no Public methods can be called by anyone---there is no access control. Methods are public by default access control. Methods are public by default (except for initialize, which is always private). (except for initialize, which is always private).
Protected methods can be invoked only by objects of Protected methods can be invoked only by objects of the defining class and its subclasses. Access is kept the defining class and its subclasses. Access is kept within the family. within the family.
Private methods cannot be called with an explicit Private methods cannot be called with an explicit receiver. Because you cannot specify an object when receiver. Because you cannot specify an object when using them, private methods can be called only in using them, private methods can be called only in the defining class and by direct descendents within the defining class and by direct descendents within that same object.”that same object.”
http://ruby-doc.org/docs/ProgrammingRuby/
– 38 – CSCE 740 Spring 2014
Specifying Access Specifying Access class MyClass class MyClass def method1 def method1 # default is 'public' # default is 'public'
#... #... end end
protected protected # subsequent methods will be 'protected' # subsequent methods will be 'protected' def method2 def method2 # will be 'protected' # will be 'protected'
#... #... end end
private private # subsequent methods will be 'private' # subsequent methods will be 'private' def method3 def method3 # will be 'private' # will be 'private'
#... #... end end
public public # subsequent methods will be 'public' # subsequent methods will be 'public' def method4 def method4 # and this will be 'public' # and this will be 'public'
#... #... end end
endend
http://ruby-doc.org/docs/ProgrammingRuby/
– 39 – CSCE 740 Spring 2014
September 11–Arrays Intro September 11–Arrays Intro
a = [ 3.14159, "pie", 99 ]a = [ 3.14159, "pie", 99 ]
a.typea.type
a[0]a[0]
a[1]a[1]
a[2]a[2]
a[3]a[3]
http://ruby-doc.org/docs/ProgrammingRuby/
– 40 – CSCE 740 Spring 2014
Ruby 1.9 Buy the book pageRuby 1.9 Buy the book page
http://pragprog.com/book/ruby3/programming-ruby-1-9http://pragprog.com/book/ruby3/programming-ruby-1-9
• Regular Expressions (download pdf)Regular Expressions (download pdf)
• Namespaces, Source Files, and Distribution Namespaces, Source Files, and Distribution (download pdf)(download pdf)
• Built-in Classes and Modules (download pdf of the Built-in Classes and Modules (download pdf of the entry for class Array)entry for class Array)
• Free Content …Free Content …
http://ruby-doc.org/docs/ProgrammingRuby/
– 41 – CSCE 740 Spring 2014
Rubular site - Regular ExpressionsRubular site - Regular Expressions
RubularRubular: a Ruby regular expression editor and tester: a Ruby regular expression editor and tester
http://rubular.com/
[abc] A single character of: a, b or c
[^abc] Any single character except: a, b, or c
[a-z] Any single character in the range a-z
[a-zA-Z]Any single character in the range a-z or A-Z
^ Start of line
$ End of line
\A Start of string
\z End of string
– 42 – CSCE 740 Spring 2014
. Any single character
\s Any whitespace character
\S Any non-whitespace character
\d Any digit
\D Any non-digit
\wAny word character (letter, number, underscore)
\W Any non-word character
\b Any word boundary
(...) Capture everything enclosed
(a|b) a or b
a? Zero or one of a
a* Zero or more of a
a+ One or more of a
a{3} Exactly 3 of a
a{3,} 3 or more of a
a{3,6} Between 3 and 6 of a
http://rubular.com/
– 43 – CSCE 740 Spring 2014
Fig 3.3 SaaS book - All objects All time Fig 3.3 SaaS book - All objects All time
SaaS book – Fox and Patterson
– 44 – CSCE 740 Spring 2014
book_in_stockbook_in_stock
class BookInStock class BookInStock
attr_reader :isbn, :priceattr_reader :isbn, :price
def initialize(isbn, price)def initialize(isbn, price)
@isbn = isbn@isbn = isbn
@price = Float(price)@price = Float(price)
end end
endend
Programming Ruby 1.9 & 2.0 - Pickaxe
– 45 – CSCE 740 Spring 2014
book_in_stockbook_in_stock
b1 = BookInStock.new("isbn1", 3)b1 = BookInStock.new("isbn1", 3)
puts b1puts b1
b2 = BookInStock.new("isbn2", 3.14)b2 = BookInStock.new("isbn2", 3.14)
puts b2puts b2
b3 = BookInStock.new("isbn3", "5.67")b3 = BookInStock.new("isbn3", "5.67")
puts b3puts b3
Programming Ruby 1.9 & 2.0 - Pickaxe
– 46 – CSCE 740 Spring 2014
book_in_stockbook_in_stock
class BookInStockclass BookInStock
def initialize(isbn, price)def initialize(isbn, price)
@isbn = isbn@isbn = isbn
@price = Float(price)@price = Float(price)
endend
def to_sdef to_s
"ISBN: #{@isbn}, price: "ISBN: #{@isbn}, price: #{@price}"#{@price}"
endend
endend
b1 = b1 = BookInStock.new("isbn1", BookInStock.new("isbn1", 3)3)
puts b1puts b1
b2 = b2 = BookInStock.new("isbn2", BookInStock.new("isbn2", 3.14)3.14)
puts b2puts b2
b3 = b3 = BookInStock.new("isbn3", BookInStock.new("isbn3", "5.67")"5.67")
puts b3puts b3Programming Ruby 1.9 & 2.0 - Pickaxe
– 47 – CSCE 740 Spring 2014
book_in_stock4book_in_stock4
class BookInStockclass BookInStock
def initialize(isbn, price)def initialize(isbn, price)
@isbn = isbn@isbn = isbn
@price = Float(price)@price = Float(price)
end end
def isbndef isbn
@isbn@isbn
endend
def pricedef price
@price@price
endend
# .. # ..
endend
book = book = BookInStock.new("isbn1", BookInStock.new("isbn1", 12.34)12.34)
puts "ISBN = puts "ISBN = #{book.isbn}"#{book.isbn}"
puts "Price = puts "Price = #{book.price}"#{book.price}"
Programming Ruby 1.9 & 2.0 - Pickaxe
– 48 – CSCE 740 Spring 2014
book_in_stock5book_in_stock5
class BookInStock class BookInStock
attr_reader :isbn, :priceattr_reader :isbn, :price
def initialize(isbn, price)def initialize(isbn, price)
@isbn = isbn@isbn = isbn
@price = Float(price)@price = Float(price)
end end
def price=(new_price)def price=(new_price)
@price = new_price@price = new_price
endend
# ...# ...
endend
book = book = BookInStock.new("isbn1", BookInStock.new("isbn1", 33.80)33.80)
puts "ISBN = puts "ISBN = #{book.isbn}"#{book.isbn}"
puts "Price = puts "Price = #{book.price}"#{book.price}"
book.price = book.price * book.price = book.price * 0.75 # discount price0.75 # discount price
puts "New price = puts "New price = #{book.price}"#{book.price}"
Programming Ruby 1.9 & 2.0 - Pickaxe
– 49 – CSCE 740 Spring 2014
book_in_stock6book_in_stock6
class BookInStock class BookInStock
attr_reader :isbnattr_reader :isbn
attr_accessor :priceattr_accessor :price
def initialize(isbn, price)def initialize(isbn, price)
@isbn = isbn@isbn = isbn
@price = Float(price)@price = Float(price)
end end
# ...# ...
endend
book = book = BookInStock.new("isbn1", BookInStock.new("isbn1", 33.80)33.80)
puts "ISBN = puts "ISBN = #{book.isbn}"#{book.isbn}"
puts "Price = puts "Price = #{book.price}"#{book.price}"
book.price = book.price * book.price = book.price * 0.75 # discount price0.75 # discount price
puts "New price = puts "New price = #{book.price}"#{book.price}"
Programming Ruby 1.9 & 2.0 - Pickaxe
– 50 – CSCE 740 Spring 2014
book_in_stock7book_in_stock7
class BookInStock class BookInStock
attr_reader :isbnattr_reader :isbn
attr_accessor :priceattr_accessor :price
def initialize(isbn, price)def initialize(isbn, price)
@isbn = isbn@isbn = isbn
@price = Float(price)@price = Float(price)
end end
def price_in_centsdef price_in_cents
Integer(price*100 + 0.5)Integer(price*100 + 0.5)
endend
# ...# ...
endend
book = book = BookInStock.new("isbn1", BookInStock.new("isbn1", 33.80)33.80)
puts "Price = puts "Price = #{book.price}"#{book.price}"
puts "Price in cents = puts "Price in cents = #{book.price_in_cents}"#{book.price_in_cents}"
Programming Ruby 1.9 & 2.0 - Pickaxe
– 51 – CSCE 740 Spring 2014
book_in_stock8book_in_stock8
class BookInStock class BookInStock
attr_reader :isbnattr_reader :isbn
attr_accessor :priceattr_accessor :price
def initialize(isbn, price)def initialize(isbn, price)
@isbn = isbn@isbn = isbn
@price = Float(price)@price = Float(price)
end end
def price_in_centsdef price_in_cents
Integer(price*100 + 0.5)Integer(price*100 + 0.5)
endend
def def price_in_cents=(cents)price_in_cents=(cents)
@price = cents / 100.0@price = cents / 100.0
endend
# ...# ...
endend
Programming Ruby 1.9 & 2.0 - Pickaxe
– 52 – CSCE 740 Spring 2014
book = BookInStock.new("isbn1", 33.80)book = BookInStock.new("isbn1", 33.80)
puts "Price = #{book.price}"puts "Price = #{book.price}"
puts "Price in cents = #{book.price_in_cents}"puts "Price in cents = #{book.price_in_cents}"
book.price_in_cents = 1234book.price_in_cents = 1234