Nils Haldenwang, M.Sc.
Gastvortrag
Datenbanksysteme:
Ruby on Rails
• plattformunabhängige General Purpose Programmiersprache
• Veröffentlichung 1995 in Japan
• außerhalb Japans bekannt geworden um 2000
• Objektorientierung
• dynamische Typisierung (Duck Typing)
• Garbagecollection
• aktuelle Version: 2.2.2
Ruby
2
Ruby
I hope to see Ruby help every programmer in the world to be productive, and to enjoy
programming, and to be happy.
That is the primary purpose of the Ruby language.
- Yukihiro Matsumoto
Ruby
Einführung in die Syntax
4
Quellen / Literaturempfehlungen
2.2.2 Core API: http://www.ruby-doc.org/core-2.2.2/
Ruby Dokumentation: http://www.ruby-doc.org/
Quellen / Literaturempfehlungen
6 Ruby
Dave Thomas Chad Fowler, Andy Hunt,
Programming Ruby 1.9 & 2.0 Pragmatic Bookshelf, 2013
Quellen / Literaturempfehlungen
Paolo Perrotta
Metaprogramming Ruby 2 Pragmatic Bookshelf, 2014
Hello World
puts "Hello World!"
Ausgabe Stringliteral
hello_world.rb
$ ruby hello_world.rb Hello World!
8 Ruby
local_variable = "Lokale Variable"
@instance_variable = "Instanzvariable"
@@class_variable = "Klassenvariable"
$global_variable = "Globale Variable"
SOME_CONSTANT = "Konstante"
SomeClass # Klassenkonstante
Variablen
Basisdatentypen
Ruby
natural_number = 42
natural_number.class # => Fixnum, konstante Zahl float_number = 42.0
float_number.class # => Float, Fließkommazahl string = "Hello World!"
string.class # => String symbol = :hello_world
symbol.class # => Symbol, konstanter String
10
Collections: Array
a = []
a = Array.new
a = [42, "foo", nil]
puts a[0] # Ausgabe: 42 puts a.size # Ausgabe: 3 a[0] = 24
Collections: Hash
h = Hash.new h = {}
h = {
:a => "b", :c => 42, "e" => "f",
42 => "The answer,..."
}
puts h[:a] # Ausgabe: b
puts h[42] # Ausgabe: The answer,..
h[:c] = 73 h = {
a: "b", c: 42 }
Ruby
Hashrocket wenn keine
Symbole
Doppelpunkt bei Symbolen
12
Demo
Methoden
def say_goodnight(name)
result = "Good night, " + name return result
end
puts( say_goodnight("John-Boy") )
# => Good night, John-Boy
puts say_goodnight "John-Boy"
puts say_goodnight("John-Boy") def say_goodnight(name)
result = "Good night, #{name}"
return result end
def say_goodnight(name) "Good night, #{name}"
end
14
Klammern optional
Rückgabewert ist der Wert
des letzten Ausdruckes.
Empfohlene Schreibweise
Bedingte Anweisungen
if x == 5
puts "x is 5"
end
puts "x is 5" if x == 5
if x == 5
puts "x is 5"
elsif x == 3
puts "x is 3"
else
puts "x is unknown"
end
Obacht!
Bedingte Anweisungen
if !( x == 5 )
puts "x isn't 5"
end
puts "x isn't 5" if !( x == 5 )
unless x == 5
puts "x is not 5"
end
puts "x is not 5" unless x == 5
16 Ruby
Schleifen
i = 42
while i > 0 puts i
i -= 1 end
i = 42
until i == 0 puts i
i -= 1 end
a = [1, 2, 3, 4, 5]
for element in a puts element
end
Collatz
Ruby
public class Collatz {
public static int value(int x){
int z = 0;
while (x != 1) { if (x % 2 == 0) x = x / 2;
else
x = 3*x+1;
z = z+1;
}
return z;
} }
18 Ruby
public class Collatz {
public static int value(int x){
int z = 0;
while (x != 1) { if (x % 2 == 0) x = x / 2;
else
x = 3*x+1;
z = z+1;
}
return z;
} }
def collatz(x) iterations = 0 while (x != 1)
if (x % 2 == 0) x = x / 2
else
x = 3*x + 1 end
iterations = iterations + 1 end
return iterations end
Collatz
def collatz(x) iterations = 0 until x == 1 if x.even?
x /= 2 else
x = 3*x + 1 end
iterations += 1 end
iterations end
Collatz
def collatz(x) iterations = 0 while (x != 1)
if (x % 2 == 0) x = x / 2
else
x = 3*x + 1 end
iterations = iterations + 1 end
return iterations end
20 Ruby
Blöcke
{ puts "Hello, Block!" } do
puts "Hello, Block!"
puts "Multiple lines."
end
Blöcke übergeben
call_block { puts "Hello, Block!" } call_block do
puts "Hello, Block!"
end
22 Ruby
Blöcke aufrufen
def call_block
puts "Calling block:"
yield yield
puts "Block has been called."
end
call_block { puts "Hello" }
# Ausgabe:
# Calling block:
# Hello
# Hello
# Block has been called.
Blöcke mit Parametern
def call_block yield("foo") end
call_block { |param| puts "Param: #{param}" } call_block do |param|
puts "Param: #{param}"
end
# Ausgabe:
# Param: foo
24 Ruby
Variablen und Blöcke
def call_block yield
end
var = 42
call_block { var = 73 } puts var
# Ausgabe: 73
Optionale Blöcke
def greet(name) if block_given?
yield name else
puts "Hello, #{name}!"
end end
greet "Joe" # Ausgabe: Hello, Joe!
greet( "Joe" ) { |name| puts "Nice to meet you, #{name}!" }
# Ausgabe: Nice to meet you, Joe!
26 Ruby
Iteratoren mit Blöcken
a = ["iterators", "rock"]
a.each { |e| puts e }
# Ausgabe:
# iterators
# rock
h = { a: 42, b: 73 }
h.each { |k, v| puts "key: #{k}, value: #{v}" }
# Ausgabe:
# key: a, value: 42
# key: b, value: 73
Schleifen mit Blöcken
3.times { |i| puts i }
# Ausgabe:
# 0
# 1
# 2
1.upto(3) { |i| puts i }
# Ausgabe:
# 1
# 2
# 3
3.downto(1) { |i| puts i }
# Ausgabe:
# 3
# 2
# 1
28 Ruby
Demo
Ruby
Installation
30
Ruby installieren
Ruby Version Manager
http://beginrescueend.com/
Ruby Installer
http://rubyinstaller.org/
Ruby
Ruby installieren mit RVM
$ rvm install 2.2.2
$ rvm use 2.2.2
$ irb
2.2.2-p0 >
32
Ruby on Rails
Ruby on Rails
• In Ruby geschriebenes Webapplication Framework
• Forciert Resource-Oriented Architecture
• Erstes Framework seiner Art
• Open Source
• 2005 Veröffentlichung Version 1.0
• Aktuelle Version: 4.2.1, erschienen im März 2015
34 Ruby on Rails
Ruby on Rails
Rails is about allowing beautiful code to solve the problems most people have most of the time in web-application development. It’s about taking the pain away and making you happy.
This might all sound mighty fluffy, but only until you recognize that the single-most important factor in programmer productivity is
motivation. And, happy programmers are certainly motivated
programmers. Thus, if you optimize for happiness, you’re optimizing for motivation, which ultimately leads to an optimization for
productivity.
Quellen/Literatur
Sam Ruby, Dave Thomas, David Heinmeier Hansson,
Agile Web Development with Rails, Pragmatic Bookshelf, 2014
Ruby on Rails
Konzepte & Design
Patterns
Model-View-Controller (MVC)
Don’t Repeat Yourself
(DRY)
Convention Over Configuration
(COC)
Ruby on Rails
Model-View-Controller (MVC)
• Design Pattern zur Strukturierung von Software-Entwicklung
• Entwicklung 1979 für Oberflächen mit Smalltalk
• De-facto-Standard für Grobentwurf vieler komplexer Softwaresysteme
• Ziel: Reduktion der Komplexität und verbesserte Wiederverwendbarkeit, Wartbarkeit, Flexibilität
• Idee: Isolation von Geschäftslogik und Userinterface und
Controller
Ruby on Rails
Model View
Observer
Geschäftslogik?
Ablaufsteuerung
Anzeige / Userinterface Datenhaltung
Model
Datenfluss und MVC in Rails
Browser Webserver Router
Controller
DB View
Rails-App
Ablauf linear
Web Application Architecture
Representational State Transfer
REST
Resource-Oriented Architecture
ROA
&
Quellen/Literatur
Fielding, Roy Thomas,
Architectural Styles and the Design of Network-based Software Architectures,
Doctoral dissertation,
University of California, Irvine, 2000
Quellen/Literatur
Web Application Architecture
Richardson, L. and Ruby, S., RESTful Web Services
O’Reilly Media, 2007
Dix, P.,
Service-Oriented Design with Ruby on Rails,
Addison-Wesley Professional, 2010
REST
• “REST is an architectural style for distributed hypermedia systems.” - Roy Fielding, 2000
• Ziele:
• Skalierbare Interaktion zwischen Komponenten und größtmögliche Unabhängigkeit
• Allgemeine Schnittstellen
• Zwischenschichten zur Verbesserung von Sicherheit, Latenz und dem Kapseln von Legacy-Systemen
ROA
• “The ROA is a way of turning a problem into a RESTful Webservice.” - L. Richardson, S. Ruby, 2007
• Rückbesinnung auf Ideen, die das Web erfolgreich gemacht haben
• Adressability & URIs
• Resources & Representations
• Statelessness
• Connectedness
• Uniform Interface Web Application
Architecture
Was sind Ressourcen?
• Dinge, die als eigene Entität referenziert oder manipuliert werden können
• Beispiele:
• Version 1.3.1 einer Software
• Die aktuelle Version einer Software
• Die nächste Primzahl nach 1024
Eine Liste von zu behebenden Bugs
Adressierbarkeit und URI
• Jede Ressource hat einen URI
• Der URI ist sowohl der Name als auch die Adresse einer Ressource
• Die URI sollte die Ressource beschreiben:
• http://www.example.com/software/releases/1.3.1.tar.gz
• http://www.example.com/software/releases/latest.tar.gz
• http://www.example.com/nextprime/1024
• http://www.example.com/bugs/by-state/open Web Application Architecture
Uniform Resource Identifier
Verschiedene Ressourcen, gleiche Daten
Zustandslosigkeit
• Jeder Request muss in völliger Isolation bearbeitet werden können und alle dafür nötigen Informationen mitliefern
• Der Server speichert keinen Client-Zustand, sondern nur Ressourcen-Zustände
• Die vom Server durchgeführte Aktion hängt nicht vom Client- Zustand ab
• Vorteile:
• Caching und Load Balancing vereinfachen sich
Repräsentationen
Teilmengen von Ressourcen-Zuständen
<person>
<name = “Nils Haldenwang” />
<description>...</description>
</person> Web Application Architecture
Manipulation von Ressourcen durch Austausch von Repräsentationen
Einheitliche Schnittstelle
“Was soll mit wem getan werden?”
GET /info.txt HTTP/1.1 Host: example.com
Zuordnung einer sinnvollen und einheitlichen Semantik zu den HTTP Verben
Semantik der HTTP Verben
GET Anfordern der Repräsenation einer Ressource
PUT Ersetzt existierende Ressource oder legt neue an übergebener URI an
POST
Annotation existenter Ressourcen, Übergabe von Daten an berechnende Prozesse und Anhängen an vorhandene
Collections
DELETE Löscht die angegebene Ressource vom Server
Web Application Architecture
HTTP Verben in Rails/ROA
URI GET PUT POST DELETE
/users Liste aller
Nutzer - Nutzer
anlegen -
/users/3
Repräsenta- tion von Nutzer 3
Update von
Nutzer 3 - Nutzer 3
löschen
Sicherheit und Idempotenz
Web Application Architecture
Ressource ändert sich nicht Wiederholte Anwedung ändert nichts
42x0 = 42x0x0x0 = 0
Verb sicher idempotent GET
PUT POST DELETE
Vorteil:
Zuverlässige Anfragen über unzuverlässiges
Netzwerk