!!! Listings zum Arikel "Edel sei der Stein"
!!! (Ruby-on-Rails-Tutorial III) von Denny Carl
!!! in iX 8/2008, S. 140
!!! Das gesamte Archiv findet sich in diesem Verzeichnis
!!! als trainspotr3.zip
!!! Listing 1: Session-Handling
def current_user
session[:current_user]
end
protected
def authenticate
authenticate_or_request_with_http_basic do |login, password|
session[:current_user] = User.authenticate(login, password)
end
end
!!! Listing 2: Rating hinzufügen
class AddRatingToTrainspot < ActiveRecord::Migration
def self.up
ActiveRecord::Base.create_ratings_table
Trainspot.add_ratings_columns
end
def self.down
Trainspot.remove_ratings_columns
ActiveRecord::Base.drop_ratings_table
end
end
!!! Listing 3: Rating anzeigen
def show_rating(trainspot)
if trainspot.rating_count > 0
return trainspot.rating_average.to_s + " / 5 Punkten"
else
return "Keine Bewertung vorhanden"
end
end
!!! Listing 4: Bewertung abgeben
<% if current_user %>
<% unless @trainspot.rated_by?(current_user) %>
Ihre Bewertung:
<% 5.times do |i| %>
<%= link_to_remote (i+1).to_s, :url => rate_trainspot_url(@trainspot, :rating => i+1) %>
<% end %>
<% end %>
<% end %>
!!! Listing 5: POST-Request
map.resources :trainspots, :member => {:rate => :post} do |trainspot|
trainspot.resources :photos
end
!!! Listing 6: render mit update-Parameter
render :update do |page|
page.replace_html 'rating', show_rating(@trainspot)
page.replace_html 'rating_input', 'Vielen Dank für Ihre Bewertung'
end
!!! Listing 7: Trainspot-Array mit Instanzen
<% trainspots.each do |trainspot| %>
-
<% if trainspot.first_photo %>
<%= link_to image_tag(trainspot.first_photo.public_filename(:thumb)), trainspot, :title => trainspot.train %>
<% else %>
<%= link_to trainspot.train, trainspot %>
<% end %>
<% end %>
!!! Listing 8: Zusätzliche Trainspot-Klassenmethoden
def self.find_newest
Trainspot.find(:all, :limit => 5, :order => 'created_at DESC')
end
def self.find_best
Trainspot.find(:all, :limit => 5, :order => 'rating_avg DESC')
end
def self.find_random
Trainspot.find(:all, :limit => 5, :order => 'RAND()')
end
!!! Listing 9: Dreimal Zugsichtungen
Die neuesten Zugsichtungen
<%= render :partial => 'shared/trainspot_list', :locals => {:trainspots => Trainspot.find_newest} %>
Die besten Zugsichtungen
<%= render :partial => 'shared/trainspot_list', :locals => {:trainspots => Trainspot.find_best} %>
Zufällig ausgewählte Zugsichtungen
<%= render :partial => 'shared/trainspot_list', :locals => {:trainspots => Trainspot.find_random} %>
!!! Listing 10: YAML-Daten
one:
id: 1
train: BR 201
location: Berlin Westhafen
user_id: 1
two:
id: 2
train: BR 201
location: Berlin Westhafen
user_id: 1
lat: 52.536821
lng: 13.343732
!!! Listing 11:
def test_trainspots_without_lng_and_lat
t = Trainspot.find 1
assert_equal false, t.valid?
end
def test_trainspots_with_lng_and_lat
t = Trainspot.find 2
assert_equal true, t.valid?
end