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
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
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
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
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
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
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
(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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
Bundler manages an application's dependencies through its entire life across many machines systematically and repeatably. Bundler manages your Gems and their dependencies 81
- 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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
What is Sass? - Syntactically Awesome Stylesheets - Standard language for css coding since rails 3.1 functionality: - Nesting - Variables - Selector Inheritance - Mixins 145
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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