Share
Embed
RubyOnRails from Scratch
3 day beginners workshop for Ruby and RubyOnRails
stephanpavlovic
January 10, 2012
Transcript
201 slides
-
Ruby On Rails / Einsteigerworkshop / Railslove / 2012 Wer
sind wir? Ralph Jan Stephan 4 -
Ruby On Rails / Einsteigerworkshop / Railslove / 2012 Wer
sind wir? Railslove GmbH aus Köln - Ein junges Team aus Web-Experten - Mit Web-Entwicklungs- und Beratungsleistungen als Agentur primär in der europäischen Start-Up-Branche tätig - Zahlen und Fakten: 16+ Mitarbeiter, 300 qm offener Coworking-Space in Köln Ralph Jan Stephan 5 -
Ruby On Rails / Einsteigerworkshop / Railslove / 2012 Ablauf
Wie läuft der Workshop zeitlich ab? - Start: ~10Uhr, Ende ~16Uhr Wie läuft der Workshop inhaltlich ab? - Abwechselnd Vortragsteile - Rundflug über die Welt von Ruby und Rails - Bei Fragen -> fragen - und Hands-On Teile - gearbeitet wird in Zweier-Gruppen - Cheat-Sheets 8 -
Ruby On Rails / Einsteigerworkshop / Railslove / 2012 Tagesplanung
Tag 1 Warm Up Ruby Grundlagen Testen in Ruby Tag 2 Rails Grundlagen Model Controller Tag 3 Views Frontend Testing Javascript 10 -
Ruby On Rails / Einsteigerworkshop / Railslove / 2012 Tagesplanung
Tag 1 Warm Up Ruby Grundlagen Testen in Ruby Tag 2 Rails Grundlagen Model Controller Tag 3 Views Frontend Testing Javascript 10 -
Ruby On Rails / Einsteigerworkshop / Railslove / 2012 Ruby:
Language characteristics -POLS (Principle of Least Surprise) -Easy to learn -Hard to master 13 -
Ruby On Rails / Einsteigerworkshop / Railslove / 2012 Ruby:
Language characteristics -Interpreted -Compiled to bytecode at runtime -Several implementations, no official spec -Potentially slow 14 -
Ruby On Rails / Einsteigerworkshop / Railslove / 2012 Ruby:
Language characteristics -"Duck typed" -Metaprogramming (code that writes code) 15 -
Ruby On Rails / Einsteigerworkshop / Railslove / 2012 Ruby:
Extensibility -Great Standard Library -Greater choice of Ruby Gems -e.g. gem install rails 16 -
Ruby On Rails / Einsteigerworkshop / Railslove / 2012 Do
try this at home ruby --version # 1.9.3 irb # open interactive ruby RUBY_VERSION # "1.9.3" puts "hello world" name = "Carlos" "hello #{name}" # "hello Carlos" exit # exit interactive ruby gem --version # >= "1.8.10" 18 -
Ruby On Rails / Einsteigerworkshop / Railslove / 2012 A
simple Ruby class # song.rb class Song def title @title end def title=(title) @title = title end end 20 -
Ruby On Rails / Einsteigerworkshop / Railslove / 2012 A
simple Ruby class irb require './song.rb' song = Song.new song.title = 'Wonderwall' song.title => "Wonderwall" 21 -
Ruby On Rails / Einsteigerworkshop / Railslove / 2012 Essential
in Ruby: Testing # song_test.rb require 'minitest/autorun' require './song.rb' class SongTest < MiniTest::Unit::TestCase def test_title_setter_and_getter song = Song.new song.title = 'Wonderwall' assert_equal 'Wonderwall', song.title end end 22 -
Ruby On Rails / Einsteigerworkshop / Railslove / 2012 Essential
in Ruby: Testing ruby song_test.rb Run options: --seed 40046 # Running tests: . Finished tests in 0.000587s, 1703.5775 tests/s, 1703.5775 assertions/s. 1 tests, 1 assertions, 0 failures, 0 errors, 0 skips 23 -
Ruby On Rails / Einsteigerworkshop / Railslove / 2012 Refactoring!
# song.rb class Song attr_accessor :title end (Also available: attr_reader and attr_writer) Do your tests still pass? 24 -
Ruby On Rails / Einsteigerworkshop / Railslove / 2012 The
initialize method Executed on every object upon initialization # song.rb class Song def initialize @title = '' @artist = '' end end 25 -
Ruby On Rails / Einsteigerworkshop / Railslove / 2012 Class
methods Defined on the class, not each instantiated object # song.rb class Song def self.create(song_hash) song = Song.new song.artist = song_hash[:artist] song end end song = Song.create({artist: 'a', title: 't'}) 26 -
Ruby On Rails / Einsteigerworkshop / Railslove / 2012 Hands
on: Ruby classes and Testing Write a Song class and accompanying tests that do the following: - Getter and setter for title and artist - artist and title default value is an empty string - Advanced: - Set the rating attribute to a value between 1 and 5 - Hint: this is a Range (maybe search the Ruby docs at http://ruby- doc.org/) - Don‘t do anything if the value supplied is outside the range - Getter for the rating attribute 28 -
Ruby On Rails / Einsteigerworkshop / Railslove / 2012 Hands
on: Ruby classes and Testing def test_artist_set_to_empty_string song = Song.new assert_equal '', song.artist end def test_title_set_to_empty_string song = Song.new assert_equal '', song.title end 29 -
Ruby On Rails / Einsteigerworkshop / Railslove / 2012 Hands
on: Ruby classes and Testing def test_set_rating_to_value_between_1_and_5 song = Song.new song.rating = 3 assert_equal 3, song.rating end def test_set_rating_to_value_outside_of_1_to_5 song = Song.new song.rating = 6 assert_equal nil, song.rating end def test_set_existing_rating_to_value_outside_of_1_to_5 song = Song.new song.rating = 3 song.rating = 6 assert_equal 3, song.rating end 30 -
Ruby On Rails / Einsteigerworkshop / Railslove / 2012 Hands
on: Ruby classes and Testing # song.rb class Song attr_accessor :title, :artist attr_reader :rating def rating=(rating) @rating = rating if (1..5).include? rating end end 31 -
Ruby On Rails / Einsteigerworkshop / Railslove / 2012 String
Common literals (How do I make one?) -'without interpolation' -"with #{interpolation}" What can you do with Strings? - Concatenate string_1 + string_2 - length - sub/sub!/gsub/gsub! - More: http://ruby-doc.org/core-1.9.3/String.html 33 -
Ruby On Rails / Einsteigerworkshop / Railslove / 2012 Symbol
(Think: String that stands for s.th.) Peculiarities: - Only instantiated once (object identity) Common literals (How do I make one?) -:my_symbol What can you do with Symbols? - Book.find(:all) - Book.find(:first) - More: http://ruby-doc.org/core-1.9.3/Symbol.html 34 -
Ruby On Rails / Einsteigerworkshop / Railslove / 2012 Array
Common literals (How do I make one?) -[1, 'text', :symbol] What can you do with Arrays? -[1,2,3] << 4 # [1, 2, 3, 4] -[1,2,3] + [4,5,6] # [1, 2, 3, 4, 5, 6] -[1,2,3].length # 3 -[4,8,7,3,7].index(7) # 2 - More: http://ruby-doc.org/core-1.9.3/Array.html 35 -
Ruby On Rails / Einsteigerworkshop / Railslove / 2012 Hash
Common literals (How do I make one?) -{:day_1 => 'Wed', :day_2 => 'Thu'} -{day_1: 'Wed', day_2: 'Thu'} What can you do with Hashes? -h[:day_1] # "Wed" -h[:day_1] = 'Superday' -h[:day_2] = {a: 'b'}; h[:tomorrow][:a] # 'b' -h.length # 2 - More: http://www.ruby-doc.org/core-1.9.3/Hash.html 36 -
Ruby On Rails / Einsteigerworkshop / Railslove / 2012 Regexp
Common literals (How do I make one?) -/^abc/ -Regexp.new('abc/yeah') #/abc\/yeah/ What can you do with Regexps? -/abc/ =~ 'I say abc dude' # 6 -'I say hello'[/(.)ay hell(.)/, 1] # "s" -'I say hello'[/(.)ay hell(.)/, 2] # "o" - More: http://ruby-doc.org/core-1.9.3/Regexp.html 37 -
Ruby On Rails / Einsteigerworkshop / Railslove / 2012 Control
Structures if/else/unless @rating = rating if (1..5).include? rating @rating = rating unless invalid_rating?(rating) if (1..5).include? rating @rating = rating else puts 'supplied rating value invalid!' end 38 -
Ruby On Rails / Einsteigerworkshop / Railslove / 2012 Control
Structures Iterators - ['one', 'two', 'three'].each {|item| puts item} - ['one', 'two', 'three'].map {|item| item.upcase} - => ["ONE", "TWO", "THREE"] - {foo: 'bar', zomg: 'rofl'}.each {|k,v| puts k.to_s + v} - foobar - zomgrofl - […].each {|item| puts item} is equivalent to […].each do |item| puts item end 39 -
Ruby On Rails / Einsteigerworkshop / Railslove / 2012 Control
Structures Iterators - Also check - collect - detect - each_index - each_with_index - each_with_object - map! - select - in the Enumerable/Array/Hash classes 40 -
Ruby On Rails / Einsteigerworkshop / Railslove / 2012 Related
Artists Implement the following functionality. Make sure you cover everything with tests! - Related artists: - Song#add_related_artist('Blur') # no double entries! - Song#related_artists # ['Beatles', 'Blur'] - Simple Hash representation - Song#to_hash # {:artist => 'Oasis', :title => 'T'} - Numbered List of related artists - Song#numbered_related_artists - ['1) Beatles', '2) Blur'] 42 -
Ruby On Rails / Einsteigerworkshop / Railslove / 2012 Related
Artists def test_add_related_artist song = Song.new song.add_related_artist('Blur') assert_equal ['Blur'], song.related_artists end def test_related_artists_is_unique song = Song.new song.add_related_artist('Blur') song.add_related_artist('Blur') assert_equal ['Blur'], song.related_artists end 43 -
Ruby On Rails / Einsteigerworkshop / Railslove / 2012 Related
Artists attr_reader :related_artists def add_related_artist(artist) @related_artists ||= [] unless @related_artists.include?(artist) @related_artists << artist end end 44 -
Ruby On Rails / Einsteigerworkshop / Railslove / 2012 Simple
Hash representation def test_to_hash song = Song.new song.artist = 'Oasis' song.title = 'T' expected = {:artist => 'Oasis', :title => 'T'} assert_equal expected, song.to_hash end def to_hash {artist: artist, title: title} end 45 -
Ruby On Rails / Einsteigerworkshop / Railslove / 2012 Numbered
List of related artists def test_numbered_related_artists s = Song.new s.add_related_artist('Beatles') s.add_related_artist('Blur') expected = ['1) Beatles', '2) Blur'] assert_equal expected, s.numbered_related_artists end 46 -
Ruby On Rails / Einsteigerworkshop / Railslove / 2012 Numbered
List of related artists def numbered_related_artists related_artists.map do |artist| "#{@related_artists.index(artist) + 1}) #{artist}" end end def numbered_related_artists numbered = [] related_artists.each_with_index do |artist, index| numbered << "#{index + 1}) #{artist}" end numbered end 47 -
Ruby On Rails / Einsteigerworkshop / Railslove / 2012 Rubygems
Default solution for packaging code Ships with Ruby 1.9, installer for Ruby 1.8 Usage: - gem install rails - fetches gems from rubygems.org (central gem repository) - installs all dependencies - gem uninstall rails - uninstalls a single gem from your local repository - does not care about dependencies 49 -
Ruby On Rails / Einsteigerworkshop / Railslove / 2012 Rubygems
Using an installed gem - normally - require 'gem_name' - special cases - file to be required may derive from gem_name, e.g. require 'active_support' #gem name: activesupport - it‘s possible to require only part of a gem, e.g. require 'active_support/inflector' 50 -
Ruby On Rails / Einsteigerworkshop / Railslove / 2012 Hands-On:
Rubygems In order to search engine optimize a database of songs, we need a Song#to_param method which returns the artist and title of a song in a URL friendly fashion. E.g. Artist: The Gaslight Anthem Title: The '59 Sound Expected result: the-gaslight-anthem-the-59-sound The activesupport gem defines the String#parameterize method that might be helpful here. Install the activesupport gem, and implement the Song#to_param method (along with tests, of course). 52 -
Ruby On Rails / Einsteigerworkshop / Railslove / 2012 Hands-On:
Rubygems # song_test.rb def test_to_param song = Song.new song.title = "The '59 Sound" song.artist = 'The Gaslight Anthem' expected = 'the-gaslight-anthem-the-59-sound' assert_equal expected, song.to_param end 53 -
Ruby On Rails / Einsteigerworkshop / Railslove / 2012 Hands-On:
Rubygems # song.rb require 'active_support/inflector' class Song def to_param "#{artist}-#{title}".parameterize end end 54 -
Ruby On Rails / Einsteigerworkshop / Railslove / 2012 Code
sharing: Inheritance require './song' class AwesomeSong < Song attr_accessor :awesomeness end 56 -
Ruby On Rails / Einsteigerworkshop / Railslove / 2012 Code
sharing: Inheritance # awesome_song_test.rb require 'minitest/autorun' require './awesome_song.rb' class AwesomeSongTest < MiniTest::Unit::TestCase def test_parent_class assert AwesomeSong.new.is_a?(Song) end def test_class assert_instance_of AwesomeSong, AwesomeSong.new end def test_awesomeness as = AwesomeSong.new as.awesomeness = 'rubylicious' assert_equal 'rubylicious', as.awesomeness end end 57 -
Ruby On Rails / Einsteigerworkshop / Railslove / 2012 Code
sharing: Mix-ins # crazyness.rb module Crazyness def crazyness 'super crazy' end end # awesome_song_test.rb class AwesomeSongTest < MiniTest::Unit::TestCase def test_crazyness as = AwesomeSong.new assert_equal 'super crazy', as.crazyness end end # awesome_song.rb require './crazyness' class AwesomeSong < Song include Crazyness end 58 -
Ruby On Rails / Einsteigerworkshop / Railslove / 2012 Inflections:
Ask an object about itself Class related examples: song.class # Song Song.ancestors # [Song, Object, Kernel, BasicObject] song.is_a? Song song.is_a? Object 60 -
Ruby On Rails / Einsteigerworkshop / Railslove / 2012 Inflections:
Ask an object about itself Instance related examples: song.methods # […] song.methods.grep /title/ => [:title, :title=] song.respond_to? :title song.method(:title).source_location => ["/Users/ralph/…/song.rb", 6] song.inspect => "#<Song:0x007fbf9c8f5080 @title="Help", @artist="Beatles">" 61 -
Ruby On Rails / Einsteigerworkshop / Railslove / 2012 Hands-On:
Inflections Load up your Song class in irb, create a new song with title and artist. Then check the following tasks: - Try the inflections you just learned. - Which methods are defined on your song object? - Where do these methods come from? 63 -
Ruby On Rails / Starterworkshop / Railslove / 2012 Day's
schedule Day 1 Warm Up Ruby Basics Testing in Ruby Day 2 Rails Basics Model Controller Day 3 Views Frontend Testing Javascript 68 -
Ruby On Rails / Starterworkshop / Railslove / 2012 Day's
schedule Day 1 Warm Up Ruby Basics Testing in Ruby Day 2 Rails Basics Model Controller Day 3 Views Frontend Testing Javascript 68 -
Ruby On Rails / Starterworkshop / Railslove / 2012 What
App do we build? 70 -
Ruby On Rails / Starterworkshop / Railslove / 2012 What
App do we build? 70 -
Ruby On Rails / Starterworkshop / Railslove / 2012 Szenario:
A microblogging service for music - I can view music recommendations of my friends on a dashboard - The dashboard can play different kinds of links (YouTube, Soundcloud), ... - I can recommend music to my friends from the dashboard - (Facebook, Twitter, Google+ integration) - Search for search songs/artists - User profiles - User settings What App do we build? 71 -
Ruby On Rails / Starterworkshop / Railslove / 2012 Brainstorming
User Song/Post Playlist 1 n 1 n n m n m 73 -
Ruby On Rails / Starterworkshop / Railslove / 2012 Ruby
On Rails MVC Framework for webapplication - written in Ruby - Model View Controller Simplifies the development - gives you basic webapplication work flows DRY - Don´t repeat yourself Convention over configuration - just (one) configuration file REST - Ressourcenorientation and standard HTTP methods 75 -
Ruby On Rails / Starterworkshop / Railslove / 2012 Rails
and MVC Modell View Controller Status change User input Status inquiry 76 -
Ruby On Rails / Starterworkshop / Railslove / 2012 Rails
and MVC Controller View Modell Status change User input Status inquiry 77 -
Ruby On Rails / Starterworkshop / Railslove / 2012 Modell
View Controller Rails and MVC Status change User input Status inquiry 78 -
Ruby On Rails / Starterworkshop / Railslove / 2012 Rails
und MVC Modell View Controller Status change User input Status inquiry 79 -
Ruby On Rails / Starterworkshop / Railslove / 2012 First
Steps Create a new project - rails new ... Configure the database - database.yml Configure gems - gemfile Start the server - rails server Start coding - rails generate ... 80 -
Ruby On Rails / Starterworkshop / Railslove / 2012 Bundler
Bundler manages an application's dependencies through its entire life across many machines systematically and repeatably. Bundler manages your Gems and their dependencies 81 -
Ruby On Rails / Starterworkshop / Railslove / 2012 Bundler
- Gemfile Source Git 82 -
Ruby On Rails / Starterworkshop / Railslove / 2012 Bundler
- Gemfile Require gem “rspec”, :require => “spec” - filename is different than gem name 83 -
Ruby On Rails / Starterworkshop / Railslove / 2012 Bundler
- Gemfile Groups Paths 84 -
Ruby On Rails / Starterworkshop / Railslove / 2012 Bundler
- Gemfile Versions >= 1.0, <= 1.0 are self-explanatory ~> has a special meaning, ~> 2.0.3 is identical to >= 2.0.3 and < 2.1. ~> 2.1 is identical to >= 2.1 and < 3.0. ~> 2.2.beta will match prerelease versions like 2.2.beta.12. 85 -
Ruby On Rails / Starterworkshop / Railslove / 2012 Rake
Rake is a simple ruby build program with capabilities similar to make Rake is a software task management tool e.g: - change your database schema - resize images - import latest currency information Task that are executed automatically and/or regular 88 -
Ruby On Rails / Starterworkshop / Railslove / 2012 Rake
common rake tasks - rake -T - rake --help - rake db:migrate - rake db:create - rake test - rake test:functional - rake my:task --trace 89 -
Ruby On Rails / Starterworkshop / Railslove / 2012 Hand
On Install rails - gem install rails Create your application - rails new MyCoolApplicationName -d mysql Configure your app - database.yml - Gemfile - bundle install Create a layout - rails g nifty:layout --haml Create some models - rails g nifty:scaffold song title:string --haml - rails g nifty:authentication --haml - rake db:migrate 91 -
Ruby On Rails / Starterworkshop / Railslove / 2012 Bringing
Power to your models Migrations - Abstracts changes to your database schema Methods - class methods, instance methods and some rails magic Validation - Conditions for a valid object Tests - Be sure your code does, what it´s suppost to do 93 -
Ruby On Rails / Starterworkshop / Railslove / 2012 Migrations
Create a migration - rails generate migration NameOfTheMigration - in the db/migrate folder a migration file is created Migrationsfile - before Rails 3.1: Two methods up and down - now: one method change Using a migration - rake db:migrate 94 -
Ruby On Rails / Starterworkshop / Railslove / 2012 Migrations
Create a migration - rails generate migration NameOfTheMigration - in the db/migrate folder a migration file is created Migrationsfile - before Rails 3.1: Two methods up and down - now: one method change Using a migration - rake db:migrate 94 -
Ruby On Rails / Starterworkshop / Railslove / 2012 Methods
Instance methods Class methods Scopes 95 -
Ruby On Rails / Starterworkshop / Railslove / 2012 Methods
Instance methods Class methods Scopes 95 -
Ruby On Rails / Starterworkshop / Railslove / 2012 Methods
Instance methods Class methods Scopes 95 -
Ruby On Rails / Starterworkshop / Railslove / 2012 Methods
Instance methods Class methods Scopes scope :top_rated, where(:rating => 5) 95 -
Ruby On Rails / Starterworkshop / Railslove / 2012 Methods
for database access dynamic find and find_by methods - Song.find(1) - Song.find_by_title(„Thrilller“) - Song.find_all_by_genre(„Pop“) Abstract database methods - Song.where(:title => „Thriller“).where(:genre => „Pop“) - Song.where(„length >= 100“) Find_by_sql - Song.find_by_sql(„SELECT * FROM ,songs‘ WHERE ,title‘ = ,Thriller‘“) 96 -
Ruby On Rails / Starterworkshop / Railslove / 2012 Validations
What are validations? - Validations are rules to secure the data integrity of a object How do validations work? - Validations are checked, when you call „save“ on an object - „save“ return true or false - save! raises an execption if the validations fail - save(false) runs save without checking the validations 97 -
Ruby On Rails / Starterworkshop / Railslove / 2012 Validations
What are validations? - Validations are rules to secure the data integrity of a object How do validations work? - Validations are checked, when you call „save“ on an object - „save“ return true or false - save! raises an execption if the validations fail - save(false) runs save without checking the validations 97 -
Ruby On Rails / Starterworkshop / Railslove / 2012 Model
Tests - Test model behaviour and database integration - Located in test/unit - Inherit from ActiveSupport::TestCase 98 -
Ruby On Rails / Starterworkshop / Railslove / 2012 Fixtures:
Sample data for tests - Regular Rails tests: with database integration - Useful: Test data to populate the test database - Default solution: Fixtures - YAML files located in test/fixtures - Automatic id and timestamp generation - access by model_name(:identifier_name) - songs(:identifier_name) song_1: title: "Wonderwall" artist: "Oasis" 99 -
Ruby On Rails / Starterworkshop / Railslove / 2012 Hand
On Methods - transfer useful methods from yesterday to your song model Migrations - add more attributes to your song model Validations - Create conditions for valid song objects Tests - Test validations and methods 101 -
Ruby On Rails / Starterworkshop / Railslove / 2012 Association
What are association? - they describe the relationship between two models - on a database level: Connecting two tables Which kinds if association exist? - has_one - belongs_to - has_many - has_and_belongs_to_many 104 -
Ruby On Rails / Starterworkshop / Railslove / 2012 Association
has_one: - 1:1 relation on an object level - The songmodel is extended with a mp3 method - takes care of the foreign key relation songs id title duration 1 1 mp3s id title song_id 105 -
Ruby On Rails / Starterworkshop / Railslove / 2012 Association
has_many: - 1:n relation on object level - The artist model is extended with a songs method - In sql: Select * from songs where artist.id = songs.artist_id artist id firstname lastname 1 n songs id title duration artist_id 106 -
Ruby On Rails / Starterworkshop / Railslove / 2012 Association
belongs_to: - Describes the foreign key class in a 1:1 or 1:n relation - The song model is extended with a artist method artist id firstname lastname 1 n songs id title duration artist_id 107 -
Ruby On Rails / Starterworkshop / Railslove / 2012 Association
has_and_belongs_to_many: - represents a n:m relation - a join table is needed - No ActiveRecord::Base Class is needed - convention: tablenames in alphabetical order with a underscore 1 n songs id title duration artist_id labels id name country city labels_songs label_id song_id 1 n 108 -
Ruby On Rails / Starterworkshop / Railslove / 2012 Hand
On New model - create a playlist model (its a list) Association - Create relations between playlists, songs and users - migrate the database with needed fields more - Methods - Validations - Tests 110 -
Ruby On Rails / Starterworkshop / Railslove / 2012 Controller
Was sind Controller? - Orgistrates the application - Connects models and views - Every controller class inherties from ApplicationController - Methods (actions)are mapped through name and HTTP method Basic actions: - new/create => Create a new object - edit/update => Edit a existing object - show => view a specific object - index => view a list of objects from a specific model - delete => delete a specific object 112 -
Ruby On Rails / Starterworkshop / Railslove / 2012 Controller
actions Result of a controller action - render: passes variables to a view - without a explizit render command rails renders the view that matches the action name - you can force a render explicitly : render „new“ - Redirect: Move to another action - redirect_to :back - redirect_to :action => „index“ 113 -
Ruby On Rails / Starterworkshop / Railslove / 2012 Routing
The first part identifies the host 114 -
Ruby On Rails / Starterworkshop / Railslove / 2012 Routing
The first part identifies the host The second part selects the controller BookingsController 114 -
Ruby On Rails / Starterworkshop / Railslove / 2012 Routing
The first part identifies the host The second part selects the controller BookingsController The third part picks the action 114 -
Ruby On Rails / Starterworkshop / Railslove / 2012 Routing
What I need to know? rake routes internal rails representation of a url like: locations_beer_index_url http method path (url without host) corresponding controller and action 115 -
Ruby On Rails / Starterworkshop / Railslove / 2012 What
I need to know? 4 HTTP most used Methods - PUT, POST, DELETE, GET CRUD - means: Create (POST/CREATE), Read (GET/SELECT), Update (PUT/ UPDATE), Delete (DELETE/DELETE) Try to do it RESTful - Use these HTTP methods and the CRUD-Pattern to keep your controllers clean Routing 116 -
Ruby On Rails / Starterworkshop / Railslove / 2012 MyApp/config/routes.rb
Basic Routing Gives us - GET, POST, PUT, DELETE methods for our Profile resource - and a ‘http://oktoberfest.com/’ URL that matches pages#landing_page Routing 117 -
Ruby On Rails / Starterworkshop / Railslove / 2012 MyApp/config/routes.rb
Optional Parameters Routing 118 -
Ruby On Rails / Starterworkshop / Railslove / 2012 MyApp/config/routes.rb
Nested Routes Routing 119 -
Ruby On Rails / Starterworkshop / Railslove / 2012 Functional
Tests for Your Controllers Functional tests are for checking if a request was successful or a controller rendered the right page or redirected to the right path 120 -
Ruby On Rails / Starterworkshop / Railslove / 2012 Functional
Tests for Your Controllers What your controllers should test? - was the web request successful? - was the user redirected to the right page? - was the user successfuly authenticated? - was the correct object stored in the response template? - was the approriate message displayed to the user in the view? 121 -
Ruby On Rails / Starterworkshop / Railslove / 2012 Functional
Tests for Your Controllers Example: Test the index action especially if the request was successfull (HTTP Response 200) and there is a valid beers instance variable (could also be an empty hash) 122 -
Ruby On Rails / Starterworkshop / Railslove / 2012 Functional
Tests for Your Controllers the ‘get’ method is available through the ActionController::TestCase inheritance, you can pass four parameters: - get(:action, {request parameters}, {session variables}, {flash values}) - request parameters, session variables, flash values are optional 123 -
Ruby On Rails / Starterworkshop / Railslove / 2012 Functional
Tests for Your Controllers 5 request types available for functional testing - get - post - put - head - delete 124 -
Ruby On Rails / Starterworkshop / Railslove / 2012 Functional
Tests for Your Controllers Example: Test that the create method will create a new beer object (physically a database record) and redirect to the particular beer. 125 -
Ruby On Rails / Starterworkshop / Railslove / 2012 Example:
Setup and Teardown - Simpelest Way - Setup your variables before each test - Teardown them after testing Functional Tests for Your Controllers 126 -
Ruby On Rails / Starterworkshop / Railslove / 2012 Common
mistakes - Test values on the wrong object - Because you’re initializing too much - Copy and Paste Controller tests - Copy a “:create” and test a “:put” because it has almost the same functionality - Testing only successful blocks and not failures - Try to prove the opposite - e.g.: A list of upcoming events shouldn’t include past events - don’t try only render the index with “events” - check if only past are rendered Functional Tests for Your Controllers 127 -
Ruby On Rails / Starterworkshop / Railslove / 2012 Hand
On Create a playlist controller - rails g controller playlists Clean up controller - remove unused actions from existing controllers - think about more actions you could need to have a better workflow Routes.rb - adapt routes.rb to your new action methods Test your controllers - write controller tests for the playlist controller - test the song controller as well 129 -
Ruby On Rails / Starterworkshop / Railslove / 2012 Day's
schedule Day 1 Warm Up Ruby Basics Testing in Ruby Day 2 Rails Basics Model Controller Day 3 Views Frontend Testing Javascript 134 -
Ruby On Rails / Starterworkshop / Railslove / 2012 Day's
schedule Day 1 Warm Up Ruby Basics Testing in Ruby Day 2 Rails Basics Model Controller Day 3 Views Frontend Testing Javascript 134 -
Ruby On Rails / Starterworkshop / Railslove / 2012 Views
What are views doing? - generate the user interface - present database values What are views located? - every controller has its own folder: app/views/controller_name - every action has a view template: app/views/controller_name/ action_name - layouts folder for static content like header, footer,... How does a view look? 136 -
Ruby On Rails / Starterworkshop / Railslove / 2012 Views
What are views doing? - generate the user interface - present database values What are views located? - every controller has its own folder: app/views/controller_name - every action has a view template: app/views/controller_name/ action_name - layouts folder for static content like header, footer,... How does a view look? 136 -
Ruby On Rails / Starterworkshop / Railslove / 2012 Layouts
What are layouts? - templates that render generall stuff (footer, header, sidebar,...) - can include a =yield Which layout is rendered? - default: app/views/layouts/controller_name - otherwise app/views/layouts/application - you can specify a layout in the render method: render ,action‘, :layout => „layout“ - you can define a layout per controller: layout ,special_layout‘ 137 -
Ruby On Rails / Starterworkshop / Railslove / 2012 Layouts
What are layouts? - templates that render generall stuff (footer, header, sidebar,...) - can include a =yield Which layout is rendered? - default: app/views/layouts/controller_name - otherwise app/views/layouts/application - you can specify a layout in the render method: render ,action‘, :layout => „layout“ - you can define a layout per controller: layout ,special_layout‘ 137 -
Ruby On Rails / Starterworkshop / Railslove / 2012 Partials
What are partials? - partials are templates, which render a reuable part of a page (lists,galleries, ...) - they keep your code dry - The name of a partial file always starts with a underscore Rendern of partials - render :partial => „folder/_partialname“ - instance variables are usable - you can paste custom variables - :object => variable (variable name = partial name) - :locals => {:variablenname => variable} 138 -
Ruby On Rails / Starterworkshop / Railslove / 2012 Partials
What are partials? - partials are templates, which render a reuable part of a page (lists,galleries, ...) - they keep your code dry - The name of a partial file always starts with a underscore Rendern of partials - render :partial => „folder/_partialname“ - instance variables are usable - you can paste custom variables - :object => variable (variable name = partial name) - :locals => {:variablenname => variable} 138 -
Ruby On Rails / Starterworkshop / Railslove / 2012 Helpers
What are helpers? - methods you can use in your views - reduces logic in your views - Every controller has a matching helper: app/helpers/ controller_name_helper.rb Standard-Helper? - e.g. for text - truncate - pluralize - e.g. to generate links - link_to - url_for 139 -
Ruby On Rails / Starterworkshop / Railslove / 2012 Helpers
What are helpers? - methods you can use in your views - reduces logic in your views - Every controller has a matching helper: app/helpers/ controller_name_helper.rb Standard-Helper? - e.g. for text - truncate - pluralize - e.g. to generate links - link_to - url_for 139 -
Ruby On Rails / Starterworkshop / Railslove / 2012 Asset
Pipeline What is the asset pipeline? - The asset pipeline provides a framework to concatenate and minify or compress JavaScript and CSS assets. It also adds the ability to write these assets in other languages such as CoffeeScript, Sass and Haml. Whats the benefit? - don´t care about assets, just use them - best example: images - rake assets:precompile. 141 -
Ruby On Rails / Starterworkshop / Railslove / 2012 Asset
Pipeline What is the asset pipeline? - The asset pipeline provides a framework to concatenate and minify or compress JavaScript and CSS assets. It also adds the ability to write these assets in other languages such as CoffeeScript, Sass and Haml. Whats the benefit? - don´t care about assets, just use them - best example: images - rake assets:precompile. 141 -
Ruby On Rails / Starterworkshop / Railslove / 2012 Haml
What is Haml? - HTML Abstraction Markup Language - Standard language for view templates since rails 3.1 Principles: - Markup should be beautiful - Markup should be DRY - Markup should be well-indented 143 -
Ruby On Rails / Starterworkshop / Railslove / 2012 Sass
What is Sass? - Syntactically Awesome Stylesheets - Standard language for css coding since rails 3.1 functionality: - Nesting - Variables - Selector Inheritance - Mixins 145 -
Ruby On Rails / Starterworkshop / Railslove / 2012 Sass:
Variables 147 -
Ruby On Rails / Starterworkshop / Railslove / 2012 Sass:
Selector Inheritance 148 -
Ruby On Rails / Starterworkshop / Railslove / 2012 Sass:
Alternative Syntax What is Scss? - new, alternative syntax for Sass - per definition: valid CSS is valid SCSS functinality: - Closer to css - same functionality then Sass 150 -
Ruby On Rails / Starterworkshop / Railslove / 2012 Sass:
Alternative Syntax What is Scss? - new, alternative syntax for Sass - per definition: valid CSS is valid SCSS functinality: - Closer to css - same functionality then Sass 150 -
Ruby On Rails / Starterworkshop / Railslove / 2012 Hand
On Create a basic layout - work with application.html.haml - create a basic page grid (header, footer, ...) Enhance your frontend - add needed field to forms and index/show pages Style your most important page - playlists#show - facts about the user - list of songs - display e.g. youtube video (how to do that) more - users#show 152 -
Ruby On Rails / Starterworkshop / Railslove / 2012 Hand
On Create a basic layout - work with application.html.haml - create a basic page grid (header, footer, ...) Enhance your frontend - add needed field to forms and index/show pages Style your most important page - playlists#show - facts about the user - list of songs - display e.g. youtube video (how to do that) more - users#show https://github.com/kylejginavan/youtube_it https://github.com/dejan/auto_html ....... 152 -
Ruby On Rails / Starterworkshop / Railslove / 2012 Testing
views assert_select - two forms of assert select - assert_select(selector, [equality], [message]) - the equality condition is met on all the selected elements through the CSS selector expression (string) - assert_select(element, selector, [equality], [message]) - the equality condition is met on all the selected elements through the selector starting from the element and its descendants - assert_select ‘title’, “welcome to musicplayer” 154 -
Ruby On Rails / Starterworkshop / Railslove / 2012 Testing
views nested assert_select - assert_select ‘ul.navigation’ do - assert_select ‘li.menu_item’ - end - the inner assert_select runs assertion on the complete collection of elements by the outer assert_select block 155 -
Ruby On Rails / Starterworkshop / Railslove / 2012 Testing
views there are several assertions you can use - assert_select_email: make assertions on a email-body - assert_select_encoded: make assertions on encoded HTML - etc. but consider to use other test frameworks for frontend testing - use rspec or controllers to test if right objects are rendered etc. - cucumber for testing complex workflows - be pragmatic, views changing often 156 -
Ruby On Rails / Starterworkshop / Railslove / 2012 Hand
On Test your most important pages - playlist#show - users#index Improve the general layout of your application 158 -
Lun Break We´ll do just a short break (20-30min) There
will be pizza! Check in your order in campfire! 159 -
Ruby On Rails / Starterworkshop / Railslove / 2012 Coffeescript
What is Coffeescript? - Language that compiles into javascript - ruby inspired syntax - Standard language for javascript coding since rails 3.1 What makes coffeescript better then pure javascript?: - Less LOC (~30%) - Better readable code - Ruby style funtionalities - “a text with a #{variable} in the middle“ - unless - ... 161 -
Ruby On Rails / Starterworkshop / Railslove / 2012 Coffeescript
variable function 162 -
Ruby On Rails / Starterworkshop / Railslove / 2012 Acts
like an api How do I get data to use it via a ajax on a view - render: create a full response to send back to the browser - redirect_to: send an HTTP redirect status code to the browser (e.g.: 301) - head: create a response consisting solely of HTTP headers to send back to the browser 165 -
Ruby On Rails / Starterworkshop / Railslove / 2012 Hand
On Enhance your dashboard with a live search - Be able to search for a song - new action - Return the song list as json - return of that action - filter songs in the dashboard - only display songs that match 167 -
Ruby On Rails / Starterworkshop / Railslove / 2012 Heroku
Heroku is a simple hoster for your app - cloud application plattform based on amazon - deploy ruby, node, cloujure, java, python and scala - just push your app to heroko - gemfile: gem ‘heroku’ && bundle install 169 -
Ruby On Rails / Starterworkshop / Railslove / 2012 Heroku
Heroku is a simple hoster for your app - cloud application plattform based on amazon - deploy ruby, node, cloujure, java, python and scala - just push your app to heroko - gemfile: gem ‘heroku’ && bundle install 169 -
Ruby On Rails / Einsteigerworkshop / Railslove / 2012 Your
lessions learned - Ruby is fun! - Rails helps you to get a running web app pretty fast - Modell, View, Controller to structure a app - Testing is important! - Haml, Sass, Coffeescript > Html, Css, Javascript 171 -
Ruby On Rails / Einsteigerworkshop / Railslove / 2012 Our
lessions learned - Your opinion? 172 -
Ruby On Rails / Einsteigerworkshop / Railslove / 2012 Challange
Task - visit api.railslove.com - build an app (Rails, Sinatra, ...) that contains - a jobs/new view with needed attributes for a job application and display the job description - a jobs/create method that sends the job application via a POST request to api.railslove.com 173 -
Ruby On Rails / Einsteigerworkshop / Railslove / 2012 Challange
Show it to us - deploy it on heroku - send us a jobposting using your app and tell us where it is on github - first “coolest”, “smartest” and “sophisticated” solution wins a 50 euro amazon voucher and maybe more 174 -
Ruby On Rails / Einsteigerworkshop / Railslove / 2012 Challange
Minimum fields - Subject => Ruby on Rails from Scratch - resumee => What did you think of the workshop - heroku_url => For us to check your app out - github_user_name 175 -
Ruby On Rails / Einsteigerworkshop / Railslove / 2012 Resources
Links - http://ruby-doc.org/ - http://rubygems.org/ - http://www.ruby-toolbox.com/ - http://api.rubyonrails.org/ Railslove - Campfire - User Groups (ruby, js, devHouse Friday, ...) - Cowoco 176