• No results found

Ruby on Rails. Computerlabor


Academic year: 2021

Share "Ruby on Rails. Computerlabor"

Show more ( Page)

Full text


Ruby on Rails



Einführung in Ruby

Einführung in Ruby on Rails





Ruby Stichworte

1995 erschienen, Open Source

Entwickelt von Yukihoro Matsumoto

Vollständig Objektorientiert


Dynamische Typbindung (Duck Typing)


Ruby Implementationen

MRI (Matz Ruby Interpret, C)


JRuby (Java)

Rubinius (Ruby)

HotRuby (JavaScript/ActionScript)


Ruby Syntax

5.times do

puts “Computerlabor” done

Alles ist ein Objekt

{} oder do ... end, () optional


Ruby Syntax


Ruby Funktionen

def zaehle(to => 100)

1.upto(100) { |i| puts i } end


Ruby Funktionen

def summiere(a, b) a+b


Ruby OO

class Auto def beschleunigen puts “Brumm” end end auto = Auto.new auto.beschleunigen


Ruby OO

class MegaAuto < Auto def bremsen puts “Quietsch” end end auto = MegaAuto.new auto.beschleunigen auto.bremsen


Ruby OO


Keine abstrakten Klassen

Mixins anstelle von Interfaces


Ruby Accessoren

class Person

attr_accessor :name attr_reader :alter


Ruby Modifikatoren


@@klassenvariable KONSTANTE

public, protected & private self


Ruby Blocks

def twice yield yield end


Ruby Blocks

def twice

yield(“Olaf”) yield(“Sergei”) end


Ruby Iteratoren

friends = ['Larry', 'Curly', 'Moe'] friends.each { |f| print f + "\n" }


Ruby on Rails


Ruby on Rails

2004, David Heinemeier Hansson

Extrahiert aus Basecamp


Ruby on Rails Prinzipien

DRY (Don’t Repeat Yourself)

Convention over Configuration


Ruby on Rails Patterns

Model View Controller


Model View


Model = Datenstruktur

View = Darstellung der Struktur Controller = Programmlogik


Active Record

Tabelle ist eine Klasse

Spalte ist ein Attribut


Active Record

class Person < ActiveRecord:Base



Person.find_by_name ‘Pascal’

Person.find_by_name_and_firstname ‘Pascal’,


Active Record Relationen

has_many + belongs_to


Active Record Migrations

class NeueTabelle < ActiveRecord::Migration

def self.up

create_table :users do |table| table.string :name

table.string :login, :null => false

table.string :password, :limit => 32, :null => false table.string :email end end def self.down drop_table :users end end


Active Record Validations

validates_acceptance_of :eula validates_associated :comments validates_presence_of :name

validates_confirmation_of :password

validates_length_of :login, :minimum => 6

validates_length_of :password, :within => 8..25

validates_numericality_of :year, :integer_only => true validates_confirmation_of :password

validates_uniqueness_of :email

validates_format_of :email, :with => /\A([^@\s]+)@((?: [-a-z0-9]+\.)+[a-z]{2,})\Z/i


Rails routes.rb

ActionController::Routing::Routes.draw do |map| map.connect 'products/:id', :controller => 'catalog', :action => 'view'

# purchase_url(:id => product.id)

map.purchase 'products/:id/purchase', :controller => 'catalog', :action => 'purchase'

map.connect '', :controller => "welcome"

# Install the default route as the lowest priority. map.connect ':controller/:action/:id.:format'

map.connect ':controller/:action/:id' end


Rails Controller

class WorldController <


def hello

render :text => 'Hello world'



Rails CRUD Controller

class BookController < ApplicationController

def list; end

def show; end

def new; end

def create; end

def edit; end

def update; end

def delete; end



Rails Controller

def list

@books = Book.find(:all)



Rails Controller

def show

@book = Book.find(params[:id])



Rails Controller

def new

@book = Book.new

@subjects = Subject.find(:all)



Rails Controller

def create

@book = Book.new(params[:book]) if @book.save

redirect_to :action => 'list' else

@subjects = Subject.find(:all) render :action => 'new'

end end


Rails Controller

def edit @book = Book.find(params[:id]) @subjects = Subject.find(:all) end


Rails Controller

def update

@book = Book.find(params[:id])

if @book.update_attributes(params[:book])

redirect_to :action => 'show', :id => @book else

@subjects = Subject.find(:all) render :action => 'edit'

end end


Rails Controller

def delete


redirect_to :action => 'list'


Rails Views

<% if @books.blank? %>

<p>There are not any books currently in the system.</p> <% else %>

<p>These are the current books in our system</p> <ul id="books">

<% @books.each do |c| %>

<li><%= link_to c.title, {:action => 'show', :id => c.id} -%></li> <% end %>


<% end %>


Rails Views

<h1>Add new book</h1>

<% form_for :book, @book, :url => { :action => "create" } do |f| %> <%= f.label :title %>

<%= f.text_field :title %><br/> <%= f.label :price %>

<%= f.text_field :price %><br/> <%= f.label :subject %>

<%= f.collection_select(:subject_id, @subjects, :id, :name) %><br/> <br/> <%= f.label :description %><br/> <%= f.text_area :description %><br/> <br/> <%= submit_tag "Create" %> <% end %>


Rails Views




Textmate, Vim, Emacs ;-)



Eclipse + RDT

Eclipse + DLTK

IntelliJ IDEA

3rd Rails






Programming Ruby (PragProg - PickAxe)

Agile Web Development with Rails (PP)

The Ruby Way (AW)

The Rails Way (AW)










REST routes.rb

map.resources :users, :sessions

map.resources :teams do |teams|

teams.resources :players


REST helpers

link_to "Destroy",


:confirm => "Are you sure?",

:method => :delete


RJS View

<%= javascript_include_tag :defaults %> <h1 id='header'>RJS Template Test</h1> <ul id='list'> <li>Dog</li> <li>Cat</li> <li>Mouse</li> </ul> <%= link_to_remote("Add a fox", :url =>{ :action => :add }) %>


RJS Controller

def add




page.insert_html :bottom, 'list',

content_tag("li", "Fox")

page.visual_effect :highlight, 'list', :duration => 3 page.replace_html 'header',


Capistrano Deployment

gem install -y capistrano

capify .


Capistrano Deployment

set :application, "set your application name here" set :repository, "set your repository location here" set :deploy_to, "/var/www/#{application}"

set :scm, :subversion

role :app, "your app-server here" role :web, "your web-server here"


Capistrano Deployment

# Initialies Setup cap deploy:setup

# Abhängigkeiten prüfen cap -q deploy:check

# Erster Deploy und Migrationen ausführen cap deploy:cold

# Weitere Deploys cap deploy

# Rollback


Related documents

We build on this growing body of research by presenting the findings of a research project that explored the effect of computer assisted language learning

Encouraged by recent calls to develop and test theory pertaining to firms from emerging economies (Meyer, 2015; Tsui, 2006; 2007; Whetten, 2009; Wright et al., 2005), we address our

MetLife Auto &amp; Home is a brand of Metropolitan Property and Casualty Insurance Company and its affiliates: Economy Preferred Insurance Company, Metropolitan Casualty

It is not intended to bind Banco Central do Brasil in its monetary or foreign exchange policy actions.. Questions and comments to gerin@bcb.gov.br or demab.codem@bcb.gov.br

Experience Rolls: If, during the course of play, you are successful with a roll for one or more of your character’s skill or characteristic resistance rolls, you should mark

PEO, Payroll and/or Benefit Plan cost analysis review Overall Human Resource Management, on or off-site Employee Relations.. Human Capital Audit Risk &amp; Safety Management

 There is no significant relationship between actual working capital and expected working capital of auto car, auto scooter, auto cycle, and auto tractor and auto two wheeler of

So Congress clearly intended that the ADA should not apply to the industrial railroad environment, and specif- ically railroad right of way. The Excursion Coordinator is the

2.55 Due to the inherent patchiness and variability in data availability for assessing biodiversity no single layer represents marine diversity adequately and it is

Would that motivate you to buy the car or truck of your dreams? I bet it might. Look, we understand that it’s been tough for everyone out there – this economy is unbelievably bad.

Let EB be the total error bound, sizeb(a) be the size in bytes for storing node a, M EL(a) be the smallest error left for any cell covered by node a (this is equal to the minimum EB −

Kenward og medarbeidere (2004) fant også at effekten av medisinsk akutteam var større for kirurgiske enn medisinske pasienter, totalt blant alle pasientene i studien fant de

We hope you’ll join us on Thursday, March 25th for our next virtual education meeting that will review “Corrosion Resistant Acid Waste Piping, Drainage &amp; Venting”, presented

(g) “Development Agreement” means an agreement entered into by the Affected Settlement Corporation, General Council and a Bidder, setting out rights and obligations of those

The Business Registries Interconnection System (BRIS) allows data to be exchanged relating to branch disclosure notifications and cross border merger notifications. However,

The aim was to define the influence of soil properties, crops and intercropping on root- and soil-associated N-cycling communities with a special focus on the genetic

• Auto dosing, auto water discharging and filling, auto water softener, inverter controlled pumps, auto cooling/heating metering by ultrasonic flow meter, and auto

Auto Insurance: An Overview Auto Insurance Options in Indiana Financial Responsibility in Indiana Voluntary/Involuntary Auto Plans Auto Insurance Premium Breakdown Auto

On Off Auto On Off Auto On Off Auto On Off Auto On Off Auto On Off Auto On Off Auto On Off Auto East Wing Fire Zones West Wing South Wing North Wing Annex Garage Basement Boiler

• If you have rendered the model on your desktop using Global Illumination , the resulting BIMx model, when viewed on a mobile device, can also be shown with Global Illumination..

❖ Ruby On Rails: Ruby is a programming language and Rails is the framework that uses Ruby. ➢ Popular blackbox