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 Max Jan Stephan Mittwoch, 9. Januar 13
Wie läuft der Workshop zeitlich ab? - Start: ~10Uhr, Ende ~15-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 Mittwoch, 9. Januar 13
initialize method Executed on every object upon initialization # item.rb class Item attr_accessor :name, :description def initialize @name = '' @description = '' end Mittwoch, 9. Januar 13
methods Defined on the class, not each instantiated object # item.rb class Item def self.create(item_hash) item = Item.new item.name = item_hash[:name] item.description = item_hash[:description] item end end the_bible = Item.create({name: 'Bible', description: 'An old book'}) Mittwoch, 9. Januar 13
on: Ruby classes and Testing Write an Item class and accompanying tests that do the following: - Getter and setter for title and description - title and title description 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 You can write tests before or after the implementation. Mittwoch, 9. Januar 13
on: Ruby classes and Testing # item.rb class Item attr_accessor :name, :description attr_reader :rating def rating=(rating) @rating = rating if (1..5).include? rating end end Mittwoch, 9. Januar 13
! -modifies the receiver 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 Mittwoch, 9. Januar 13
(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 Mittwoch, 9. Januar 13
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 Mittwoch, 9. Januar 13
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[:day2][:a] # 'b' -h.length # 2 - More: http://www.ruby-doc.org/core-1.9.3/Hash.html Mittwoch, 9. Januar 13
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 Mittwoch, 9. Januar 13
Implement the following functionality. Make sure you cover everything with tests! - add creators: - Item#add_owner('God') # no double entries! - Item#owners # ['God', 'Markus'] - Simple Hash representation - Item#to_hash # {name: 'Bible', description: 'A really old book'} - Numbered List of similar items - Item#numbered_owners - ['1) God', '2) Markus'] Mittwoch, 9. Januar 13
List of related owners def numbered_owners owners.map do |owner| "#{@owners.index(owner) + 1}) #{owner}" end end def numbered_owners numbered = [] owners.each_with_index do |owner, index| numbered << "#{index + 1}) #{owner}" end numbered end def numbered_owner owners.map.with_index do |owner, index| "#{index+1}) #{owner}" end end Mittwoch, 9. Januar 13
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 Mittwoch, 9. Januar 13
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' Mittwoch, 9. Januar 13
sharing: Mix-ins # crazyness.rb module Crazyness def crazyness 'super crazy' end end # awesome_item_test.rb class AwesomeItemTest < MiniTest::Unit::TestCase def test_crazyness ai = AwesomeItem.new assert_equal 'super crazy', ai.crazyness end end # awesome_item.rb require './crazyness' class AwesomeSong < Song include Crazyness end Mittwoch, 9. Januar 13
App do we build? Szenario: A lending tracker - I can add items that I borrow to friends - I wanna track which items are currently out - I can search and filter items by categories Mittwoch, 9. Januar 13
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 Mittwoch, 9. Januar 13
Steps Create a new project - rails new ... Configure the database - database.yml Configure gems - gemfile Start the server - rails server Start coding - rails generate ... Mittwoch, 9. Januar 13
Bundler manages an application's dependencies through its entire life across many machines systematically and repeatably. Bundler manages your Gems and their dependencies Mittwoch, 9. Januar 13
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 Mittwoch, 9. Januar 13
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 Mittwoch, 9. Januar 13
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 Mittwoch, 9. Januar 13
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 Mittwoch, 9. Januar 13
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(:validate => false) runs save without checking the validations Mittwoch, 9. Januar 13
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(:validate => false) runs save without checking the validations Mittwoch, 9. Januar 13
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) - cities(:cologne) Mittwoch, 9. Januar 13
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) - cities(:cologne) # cities.yml cologne: name: "Köln" center_lat: 50.93 center_long: 6.96 description: | Die schönste Stadt der Welt Mittwoch, 9. Januar 13
Cuurent Implementation: FactoryGirl - ThoughtBot Advantages: Object are only described once, can be modified to zour needs Factories are local, in one test only the relevant objects are loaded Mittwoch, 9. Januar 13
Cuurent Implementation: FactoryGirl - ThoughtBot Advantages: Object are only described once, can be modified to zour needs Factories are local, in one test only the relevant objects are loaded FactoryGirl.define do factory :city do name "New York" center_lat "20.34" center_long "80.872" description "Tolle Stadt" end end Mittwoch, 9. Januar 13
Cuurent Implementation: FactoryGirl - ThoughtBot Advantages: Object are only described once, can be modified to zour needs Factories are local, in one test only the relevant objects are loaded FactoryGirl.define do factory :city do name "New York" center_lat "20.34" center_long "80.872" description "Tolle Stadt" end end FactoryGirl.create(:city, name: "Köln", center_lat: 50.93, center_long: 6.96) Mittwoch, 9. Januar 13
On Useful methods for items - transfer useful methods from this morning to your item model - add useful scopes Migrations - add more attributes to your item model Validations - Create conditions for valid item objects Tests - Test validations and methods Mittwoch, 9. Januar 13
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 Mittwoch, 9. Januar 13
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 Mittwoch, 9. Januar 13
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 Mittwoch, 9. Januar 13
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 Mittwoch, 9. Januar 13
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 Mittwoch, 9. Januar 13
On New models (rails g model) - create an user and a lending model Association - Create relations between users, items and lendings - migrate the database with needed fields Validations Methods Tests Mittwoch, 9. Januar 13
What are 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 Mittwoch, 9. Januar 13
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“ - redirect_to items_path Mittwoch, 9. Januar 13
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 Mittwoch, 9. Januar 13
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 Mittwoch, 9. Januar 13
Basic Routing Gives us - GET, POST, PUT, DELETE methods for our Profile resource - and a ‘http://oktoberfest.com/’ URL - matches pages#landing_page - make sure you delete public/index.html !!! Routing Mittwoch, 9. Januar 13
On Create a location controller - rails g resource lending 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 Mittwoch, 9. Januar 13
What is Haml? - HTML Abstraction Markup Language Principles: - Markup should be beautiful - Markup should be DRY - Markup should be well-indented Mittwoch, 9. Januar 13
What is Sass? - Syntactically Awesome Stylesheets - Standard language for css coding since rails 3.1 functionality: - Nesting - Variables - Selector Inheritance - Mixins Mittwoch, 9. Januar 13
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 Mittwoch, 9. Januar 13
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 Mittwoch, 9. Januar 13
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? Mittwoch, 9. Januar 13
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? Mittwoch, 9. Januar 13
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‘ Mittwoch, 9. Januar 13
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‘ Mittwoch, 9. Januar 13
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} Mittwoch, 9. Januar 13
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} Mittwoch, 9. Januar 13
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 Mittwoch, 9. Januar 13
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 Mittwoch, 9. Januar 13
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. Mittwoch, 9. Januar 13
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. Mittwoch, 9. Januar 13
On Convert your appliation.html.erb to Haml Add a header with navigation and a fancy logo - also done in the application.html.haml Create a view to create a new lending Mittwoch, 9. Januar 13
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 - ... Mittwoch, 9. Januar 13
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 Mittwoch, 9. Januar 13
On Enhance your dashboard with a live search - Be able to search for a item - new action - Return the item list as json - return of that action - filter items in the dashboard - only display items that match Mittwoch, 9. Januar 13
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 Mittwoch, 9. Januar 13
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 Mittwoch, 9. Januar 13
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 Mittwoch, 9. Januar 13
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 Mittwoch, 9. Januar 13
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 Mittwoch, 9. Januar 13
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 Mittwoch, 9. Januar 13