• Share
  • Email
  • Embed
  • Like
  • Save
  • Private Content
Intro to Ruby on Rails
 

Intro to Ruby on Rails

on

  • 2,110 views

A brief introduction to Ruby on Rails.

A brief introduction to Ruby on Rails.

Statistics

Views

Total Views
2,110
Views on SlideShare
2,103
Embed Views
7

Actions

Likes
1
Downloads
27
Comments
0

3 Embeds 7

http://www.slideshare.net 4
http://www.linkedin.com 2
http://www.techgig.com 1

Accessibility

Categories

Upload Details

Uploaded via as Microsoft PowerPoint

Usage Rights

© All Rights Reserved

Report content

Flagged as inappropriate Flag as inappropriate
Flag as inappropriate

Select your reason for flagging this presentation as inappropriate.

Cancel
  • Full Name Full Name Comment goes here.
    Are you sure you want to
    Your message goes here
    Processing…
Post Comment
Edit your comment

    Intro to Ruby on Rails Intro to Ruby on Rails Presentation Transcript

    • Intro to Ruby on Rails
      • by Mark Menard
      • Vita Rara, Inc.
    • Ruby © Vita Rara, Inc. “ I always knew one day Smalltalk would replace Java. I just didn’t know it would be called Ruby.” - Kent Beck, Creator of “Extreme Programming”
    • Ruby on Rails
      • Ruby on Rails is astounding. Using it is like watching a kung-fu movie, where a dozen bad-ass frameworks prepare to beat up the little newcomer only to be handed their asses in a variety of imaginative ways.
      • -Nathan Torkington,
      • O'Reilly Program Chair for OSCON
      © Vita Rara, Inc.
    • The Elevator Pitch
      • Ruby on Rails is an open-source web framework that is optimized for programmer happiness and sustainable productivity. It lets you write beautiful code by favoring convention over configuration.
      © Vita Rara, Inc.
    • Overview
      • Rails is a full stack web framework
        • Model: ActiveRecord
          • ORM
          • database connectivity
          • Database schema management
        • View: ActiveView
          • View layer
          • Templates
        • Controller: ActionController
          • Web controller framework
          • Manages web integration
        • Active Support
          • Extensions to Ruby to support web development
        • Integrated Ajax support
      © Vita Rara, Inc.
    • The Rails Philosophy
      • Ruby - less and more readable code, shorter development times, simple but powerful, no compilation cycle.
      • Convention over configuration
      • Predefined directory structure, and naming conventions
      • Best practices: MVC, DRY, Testing
      • Almost everything in Rails is Ruby code (SQL and JavaScript are abstracted)
      • Integrated AJAX support. Web services with REST.
      • Good community, tools, and documentation
      • Extracted from a real application: Basecamp
      © Vita Rara, Inc.
    • Rake: The Ruby Make
      • Rake lets you define a dependency tree of tasks to be executed.
      • Rake tasks are loaded from the file Rakefile
      • Rake automates and simplifies creating and managing the development of a Rails project.
      © Vita Rara, Inc.
    • Environments
      • Rails has support for multiple execution environments.
      • Environments encapsulate database settings and other configuration.
      • Typical environments
        • Development
        • Test
        • Production
      • Additional environments are easy to add.
      © Vita Rara, Inc.
    • Migrations
      • Managing Schema Evolution
    • Managing Data Schemas
      • Rails includes support for migrations to manage the evolution of your database schema.
        • No need to write SQL.
        • Migrations use a database independent Ruby API.
        • Migrations are Ruby scripts giving you access to the full power of the language.
      © Vita Rara, Inc.
    • Migrations
      • Typical migration functions:
        • create_table
        • add_column
        • change_column
        • rename_column
        • rename_table
        • add_index
      © Vita Rara, Inc.
    • Migration Example © Vita Rara, Inc. create_table "users" , :force => true do |t| t.string :login, :email, :remember_token t.string :salt, :crypted_password, :limit => 40 t.timestamps t.datetime :remember_token_expires_at end
    • ActiveRecord
      • Modeling the World
    • Fundamentals
      • One database table maps to one Ruby class
      • Table names are plural and class names are singular
      • Database columns map to attributes, i.e. get and set methods, in the model class
      • All tables have an integer primary key called id
      • Database tables are created with migrations
      © Vita Rara, Inc.
    • ActiveRecord Model Example © Vita Rara, Inc. create_table &quot;persons&quot; do |t| t.string :first_name, last_name t.timestamps end class Person < ActiveRecord::Base end p = Person.new p.first_name = ‘Mark’ p.last_name = ‘Menard’ p.save
    • CRUD
      • Create: create, new
      • Read: find, find_by_<attribute>
      • Update: save, update_attributes
      • Delete: destroy
      © Vita Rara, Inc.
    • Finding Models
      • User.find(:first)
      • User.find(:all)
      • User.find(1)
      • User.find_by_login(‘mark’)
      • User.find(:all, :conditions => [ “login = ? AND password = ?”, login, password])
      © Vita Rara, Inc.
    • Advanced Finding
      • Finders also support:
        • :limit
        • :offset
        • :order
        • :joins
        • :select
        • :group
      © Vita Rara, Inc.
    • Update
      • user = User.find(1)
      • user.first_name = ‘Mark’
      • user.last_name = ‘Menard’
      • user.save!
      © Vita Rara, Inc.
    • Transactions
      • Account.transaction do
      • account1.deposit(100)
      • account2.withdraw(100)
      • end
      © Vita Rara, Inc.
    • ActiveRecord Associations
      • Joining Things Together
    • ActiveRecord Associations
      • Two primary types of associations:
        • belongs_to
        • has_one / has_many
      • There are others, but they are not commonly used.
      © Vita Rara, Inc.
    • ActiveRecord Associations © Vita Rara, Inc. # Has Many class Order < ActiveRecord::Base has_many :order_line_items end class OrderLineItem < ActiveRecord::Base belongs_to :order end # Has One class Party < ActiveRecord::Base has_one :login_credential end class LoginCredential < ActiveRecord::Base belongs_to :party end
    • Association Methods
      • Associations add methods to the class.
        • This is an excellent example of meta-programming.
      • Added methods allow easy management of the associated models.
        • order.order_line_items << line_item
        • order.order_line_items.create()
      © Vita Rara, Inc.
    • ActiveRecord Validations
      • Keeping Your Data Safe
    • Validation
      • Validations are rules in your model objects to help protect the integrity of your data
      • Validation is invoked by the save method. Save returns true if validations pass and false otherwise.
      • If you invoke save! then a RecordInvalid exception is raised if the object is not valid
      • Use save(false) if you need to turn off validation
      © Vita Rara, Inc.
    • Validation Callback Methods
      • validate
      • validate_on_create
      • validate_on_update
      © Vita Rara, Inc.
    • Validation Example © Vita Rara, Inc. class Person < ActiveRecord::Base def validate puts “validate invoked” end def validate_on_create puts “validate_on_create invoked” end def validate_on_update puts “validate_on_update invoked” end end peter = Person.create(:name => “Peter”) # => validate, validate_on_create invoked peter.last_name = “Forsberg” peter.save # => validate_on_update invoked
    • Validation Macros
      • validates_acceptance_of
      • validate_associated
      • validates_confirmation_of validates_each
      • validates_exclusion_of
      • validates_format_of
      • validates_inclusion_of
      • validates_length_of
      • validates_numericality_of
      • validates_presence_of
      • validates_size_of
      • validates_uniqueness_of
      © Vita Rara, Inc.
    • Validation Macro Example © Vita Rara, Inc. class User < ActiveRecord::Base validates_presence_of :name, :email, :password validates_format_of :name, :with => /^ w +$/ , :message => “may only contain word characters” validates_uniqueness_of :name, :message => “is already in use” validates_length_of :password, :within => 4 .. 40 validates_confirmation_of :password validates_inclusion_of :role, :in => %w(super admin user) , :message => “must be super , admin, or user”, :allow_nil => true validates_presence_of :customer_id, :if => Proc. new { |u| %w(admin user) .include?(u.role) } validates_numericality_of :weight, :only_integer => true, :allow_nil => true end
    • ActionController
      • The “C” in MVC
    • Controllers
      • Controllers are Ruby classes that live under app/ controllers
      • Controller classes extend ActionController::Base
      • An action is a public method and/or a corresponding view template
      © Vita Rara, Inc.
    • Rendering a Response
      • A response is rendered with the render command
      • An action can only render a response once
      • Rails invokes render automatically if you don’t
      • Redirects are made with the redirect_to command
      © Vita Rara, Inc.
    • A Simple Controller © Vita Rara, Inc. class PrioritiesController < InternalController def show @priority = current_account.priorities.find(params[:id]) end def new @priority = Priority. new end def create @priority = Priority. new (params[:priority]) if @priority.save flash[:notice] = 'The priority was successfully created.' redirect_to account_url else render :action => &quot;new&quot; end end ... end
    • Sessions
      • A hash stored on the server, typically in a database table or in the file system.
      • Keyed by the cookie _session_id
      • Avoid storing complex Ruby objects, instead put id:s in the session and keep data in the database, i.e. use session[:user_id] rather than session[:user]
      © Vita Rara, Inc.
    • ActionView
      • Our Face to the World
    • What is ActionView?
      • ActionView is the module in the ActionPack library that deals with rendering a response to the client.
      • The controller decides which template and/or partial and layout to use in the response
      • Templates use helper methods to generate links, forms, and JavaScript, and to format text.
      © Vita Rara, Inc.
    • Where do templates live?
      • Templates that belong to a certain controller typically live under app/view/controller_name, i.e. templates for Admin::UsersController would live under app/ views/admin/users
      • Templates shared across controllers are put under app/views/shared. You can render them with render :template => ‘shared/my_template’
      • You can have templates shared across Rails applications and render them with render :file => ‘path/to/template’
      © Vita Rara, Inc.
    • Template Environment
      • Templates have access to the controller object’s flash, headers, logger, params, request, response, and session.
      • Instance variables (i.e. @variable) in the controller are available in templates
      • The current controller is available as the attribute controller.
      © Vita Rara, Inc.
    • Embedded Ruby
      • <%= ruby code here %> - Evaluates the Ruby code and prints the last evaluated value to the page.
      • <% ruby code here %> - Evaluates Ruby code without outputting anything to the page.
      © Vita Rara, Inc.
    • Example View © Vita Rara, Inc. <p> <b>Name:</b> <%=h @category.name %> </p> <%= link_to 'Edit' , edit_category_path(@category) %> | <%= link_to 'Back' , categories_path %>
    • A Check Book Ledger Example
    • Basic Requirements
      • The System should allow the management of multiple accounts
      • The system should maintain an account ledger for every account in the system.
      • Each account ledger should consist of ledger entries.
      • Each ledger entry can be either a positive or negative value.
      • Ledger entries can be associated with a payee and a category.
      © Vita Rara, Inc.
    • Implementing a Check Book Ledger
      • Create a new project
      • Theme the project
      • Define our resources using: script/generate scaffold
        • Account
        • Ledger Entry
        • Payee
        • Category
      • Theme models
      • Implement
      © Vita Rara, Inc.
    • Shameless Self Promotion
    • Ruby and Rail Training
      • One day to three day programs.
      • Introduction to Ruby
      • Advanced Ruby
      • Introduction to Rails
      • Advanced Rails
      • Test Driven Development
      • Behavior Driven Development
      • Test Anything with Cucumber
      • Advanced Domain Modeling with ActiveRecord
      • Domain Driven Development with Rails
      © Vita Rara, Inc.
    • Ruby on Rails Consulting
      • Full Life Cycle Project Development
        • Inception
        • Implementation
        • Deployment
        • Long Term Support
      • Ruby on Rails Mentoring
        • Get your team up to speed using Rails
      © Vita Rara, Inc.
    • Contact Information
      • Mark Menard
        • [email_address]
        • http://www.vitarara.net /
        • 518 369 7356
      © Vita Rara, Inc.