• Like

Loading…

Flash Player 9 (or above) is needed to view presentations.
We have detected that you do not have it on your computer. To install it, go here.

Ruby on Rails, Girl Develop It, 1/4

  • 1,278 views
Uploaded on

First presentation for Girl Develop It, includes introduction to Ruby and Rails

First presentation for Girl Develop It, includes introduction to Ruby and Rails

More in: Technology
  • Full Name Full Name Comment goes here.
    Are you sure you want to
    Your message goes here
    Be the first to comment
    Be the first to like this
No Downloads

Views

Total Views
1,278
On Slideshare
0
From Embeds
0
Number of Embeds
0

Actions

Shares
Downloads
13
Comments
0
Likes
0

Embeds 0

No embeds

Report content

Flagged as inappropriate Flag as inappropriate
Flag as inappropriate

Select your reason for flagging this presentation as inappropriate.

Cancel
    No notes for slide
















































Transcript

  • 1. RUBY ON RAILS #1 Avi Flombaum for Girl Develop It, Nov 8th 2010
  • 2. CLASSES AND OBJECTS class Car avis_car = Car.new avis_car.open_door def open_door "door is open" end end Terms Classes Objects / Instances Variables Methods
  • 3. CLASSES AND OBJECTS class Car def open_door "door is open" end end class SportsCar < Car def drive_fast "vroom vroom!" end end
  • 4. BASIC RUBY TYPES String a = String.new('Hello') b = "World" a_b = a + b hello_world = "#{a} #{b}" Ranges Symbols :i_am_a_symbol :"I behave like a string" :the_difference_is_complicated :commonly_used_as_keys_in_hashes
  • 5. BASIC RUBY TYPES Array [1,2,3] alphabet = Array.new alphabet[0] = 'a' alphabet[1] = 'b' alphabet[2] = 'c' alphabet + [1,2,3] Hashes {1 => 'a', 2 => 'b', 3 => 'c'} alphabet = Hash.new alphabet[:a] = 1 alphabet[:b] = 2 alphabet[:c] = 3
  • 6. RUBY VARIABLES Local Variables A variable whose name begins with a lowercase or underscore a local variable or method invocation. A local variable is only accessible from within the block of its initialization. avi = 'awesome' def keith # scope gate puts defined?(avi) # false keiths_var = 'even awesomer, yet local' end avi keith keiths_var Scope Gate Scope defines where in a program a variable is accessible.
  • 7. RUBY VARIABLES Scope Gate Scope defines where in a program a variable is accessible.
  • 8. RUBY VARIABLES Instance Variables Instance variables begin with the @ sign and are local to the specific instance of an object. If a Car class contains an instance variable @speed, each instance of that class has its own @speed variable class Car attr_accessor :speed def speed=(val) @speed = val end def speed @speed end end hybrid = Car.new hybrid.speed = 30 ferrari = Car.new ferrari.speed = 100 hybrid.speed ferrari.speed @speed
  • 9. RUBY VARIABLES Global Variables Global variables in Ruby are accessible from anywhere in the Ruby program, regardless of where they are declared.
  • 10. RUBY VARIABLES Constants Ruby constants are values which, once assigned a value, should not be changed. Constants declared within a class or module are available anywhere within the context of that class or module. Constants declared outside of a class or module are assigned global scope. A1 = 'a1' class A A2 = 'a2' class B def go A2 end end end instance_of_b = A::B.new‚Ä® a2 = A::A2 instance_of_b.go A1 A2
  • 11. RUBY VARIABLES Constants
  • 12. RUBY ON RAILS? •Web Framework built on Ruby •Open Source •Model-View-Controller •Object-Relational Mapping •Convention Over Configuration •Don’t Repeat Yourself •REST GitHub Twitter GroupOn
  • 13. OUR SAMPLE APP An application where you can log what you have done. You can input the tasks you’ve accomplished.
  • 14. APP GENERATION rails new todo_app --skip-prototype
  • 15. APP GENERATION rails new todo_app --skip-prototype
  • 16. UNDERSTANDING M-V-C The model manages the behavior and data of the application domain, responds to requests for information about its state class Todo < ActiveRecord::Base validates_presence_of :description def self.new_from_tweet(tweet_json) todo = Todo.new( :description => tweet_json[:tweet_text]) end def complete? return true if @completed end end app/models/todo.rb
  • 17. UNDERSTANDING M-V-C The view renders the model into a form suitable for interaction, typically a user interface element. <%= form_for(@todo) do |f| %> <% if @todo.errors.any? %> <div id="error_explanation"> <h2><%= pluralize(@todo.errors.count, "error") %> prohibited this todo from being saved:</h2> <ul> <% @todo.errors.full_messages.each do |msg| %> <li><%= msg %></li> <% end %> </ul> </div> <% end %> <div class="field"> <%= f.label :description %><br /> <%= f.text_area :description %> </div> <div class="actions"> <%= f.submit %> </div> <% end %>
  • 18. UNDERSTANDING M-V-C The controller receives input and initiates a response by making calls on model objects. class TodosController < ApplicationController # POST /todos # POST /todos.xml def create @todo = Todo.new(params[:todo]) respond_to do |format| if @todo.save format.html { redirect_to(@todo, :notice => 'Todo was successfully created.') } format.xml { render :xml => @todo, :status => :created, :location => @todo } format.js else format.html { render :action => "new" } format.xml { render :xml => @todo.errors, :status => :unprocessable_entity } end end end end app/controllers/todos_controller.rb
  • 19. APP GENERATION application_controller.rb, quests_controller.rb class ApplicationController < ActionController::Base protect_from_forgery end app/controllers/application_controller.rb class TodosController < ApplicationController # GET /todos # GET /todos.xml def index @todos = Todo.all end end app/controllers/todos_controller.rb inheritance, business logic, request cycle
  • 20. APP GENERATION layouts, application.html.erb <!DOCTYPE html> <html> <head> <title>TodoApp</title> <%= stylesheet_link_tag :all %> <%= javascript_include_tag :defaults %> <%= csrf_meta_tag %> </head> <body> <%= yield %> </body> </html> app/views/layouts/application.html.erb <% expression = 'code' + 'no output' %> <%= "#{expression} -- #{Time.now}" %> <%# comment -- useful in testing %>
  • 21. SIMPLE CONFIGURATION database.yml (YAML) # SQLite version 3.x # gem install sqlite3-ruby (not necessary on OS X Leopard) development: adapter: sqlite3 database: db/development.sqlite3 pool: 5 timeout: 5000 # Warning: The database defined as "test" will be erased and # re-generated from your development database when you run "rake". # Do not set this db to the same as development or production. test: adapter: sqlite3 database: db/test.sqlite3 pool: 5 timeout: 5000 production: adapter: sqlite3 database: db/production.sqlite3 pool: 5 timeout: 5000
  • 22. START YOUR ENGINES rails server
  • 23. START YOUR ENGINES rails server
  • 24. THE TODO RESOURCE What’s a RESTful Web Service? A simple web service implemented using HTTP and the principles of REST. It is a collection of resources, with three defined aspects: • the base URI for the web service, http:// todo.app/todos •the MIME types of the data supported by the web service. This is often HTML, JSON, XML but can be any other valid MIME type. •the set of operations supported by the web service using HTTP methods. (POST, GET, PUT, DELETE)
  • 25. THE TODO RESOURCE CRUD, REST, HTTP, Controllers HTTP GET PUT POST DELETE DB READ UPDATE CREATE DELETE Rails show, index update create destroy URLs /todos, /todos/1 /todos/1 /todos /todos/1 The todo resource should account for all the interactions our application will provide to the todo object. We should be able to list todos, to show a todo, to create a new todo, to edit a todo and to delete a todo.
  • 26. THE TODO RESOURCE rails generate -h
  • 27. THE TODO RESOURCE rails generate resource -h
  • 28. THE TODO RESOURCE rails generate resource todo description:text
  • 29. THE TODO MIGRATION 201001108175359_create_todos.rb class CreateTodos < ActiveRecord::Migration def self.up • DSL (domain specific language) create_table :todos do |t| t.text :description •Transactional Transformation t.timestamps •Database Agnostic end end def self.down drop_table :todos end end
  • 30. THE TODO MIGRATION 201001108175359_create_todos.rb class CreateTodos < ActiveRecord::Migration Up/Down Methods def self.up create_table :todos do |t| create_table t.text :description change_table t.timestamps drop_table end add_column end change_column def self.down rename_column drop_table :todos end remove_column end add_index remove_index
  • 31. THE TODO MIGRATION 201001108175359_create_todos.rb class CreateTodos < ActiveRecord::Migration Column Types def self.up create_table :todos do |t| primary_key t.text :description string t.timestamps text end integer end float def self.down decimal drop_table :todos end datetime end timestamp time date binary boolean
  • 32. THE TODO MIGRATION rake db:migrate CREATE TABLE "todos" ("id" INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, "description" text, "created_at" datetime, "updated_at" datetime) the migration gives our db a structure to store the model’s data
  • 33. THE TODO RESOURCE rails generate resource todo description:text
  • 34. THE TODO MODEL app/models/todo.rb class Todo < ActiveRecord::Base end
  • 35. THE TODO MODEL Classes and Objects in Ruby class Todo end
  • 36. THE RAILS CONSOLE rails console
  • 37. THE TODO MODEL Classes and Objects in Ruby class Todo def description=(text) @description = text end def status? return @status.to_s end def complete! @status = :complete end end
  • 38. THE TODO MODEL app/models/todo.rb class Todo < ActiveRecord::Base end The ActiveRecord ORM •Lifecycle •Attributes AR.new, AR.destroy, AR.save AR.description, AR.attributes •Querying •Callbacks AR.find, AR.first, AR.last, AR.where after_save, before_create •Relationships •Validations has_many, belongs_to validates_presence_of,
  • 39. THE TODO MODEL app/models/todo.rb
  • 40. THE TODO MODEL app/models/todo.rb where joins incomplete_todos = Todo.find(:all, :conditions => {:status => :incomplete}, select includes :order => 'created_at DESC', :limit => 20) group lock order readonly incomplete_todos = Todo.where(:status => :incomplete). order('created_at DESC'). limit from limit(20) offset
  • 41. THE TODO RESOURCE rails generate resource todo description:text
  • 42. THE TODO CONTROLLER routes.rb TodoApp::Application.routes.draw do class ApplicationController < ActionController::Base resources :todos protect_from_forgery def foo # The priority is based upon order of creation render :text => 'bar' # first created -> highest priority. end end # Sample of regular route: match 'aviflombaum' => 'application#foo' # Keep in mind you can assign values other than :controller and :action # Sample of named route: # match 'products/:id/purchase' => 'catalog#purchase', :as => :purchase # This route can be invoked with purchase_url(:id => product.id) # You can have the root of your site routed with "root" # just remember to delete public/index.html. root :to => "application#foo" # See how all your routes lay out with "rake routes" # This is a legacy wild controller route that's not recommended for RESTful applications. # Note: This route will make all actions in every controller accessible via GET requests. match ':controller(/:action(/:id(.:format)))' end
  • 43. THE TODO CONTROLLER routes.rb class ApplicationController < ActionController::Base protect_from_forgery def foo render :text => 'bar' end end
  • 44. THE TODO CONTROLLER routes.rb TodoApp::Application.routes.draw do resources :todos end HTTP GET PUT POST DELETE DB READ UPDATE CREATE DELETE Rails show, index update create destroy URLs /todos, /todos/1 /todos/1 /todos /todos/1