SlideShare a Scribd company logo
1 of 40
Download to read offline
101
     1.9.2

             Ruby
             on
                          3.0.5
             Rails

          @claytonlz - Desert Code Camp 2011.1 - http://spkr8.com/t/7007




Saturday, April 2, 2011
Ecosystem
                  Models
                  Controllers
                  Views
                  Deploying & Optimizing
                  Resources for Learning


Saturday, April 2, 2011
Community

Saturday, April 2, 2011
“This sure is a nice fork,
                           I bet I could… HOLY
                             SHIT A KNIFE!”




Saturday, April 2, 2011
Opinionated

Saturday, April 2, 2011
“I flippin’ told you MVC
                           is the only way to build
                           web apps! Teach you to
                                 doubt DHH!”




Saturday, April 2, 2011
Rapid
Development
Saturday, April 2, 2011
“These goats are okay,
                           but I really need a yak
                          for some quality shaving”




Saturday, April 2, 2011
Ecosystem
                  Models
                  Controllers
                  Views
                  Deploying
                  Resources for Learning


Saturday, April 2, 2011
Models

                  Associations
                  Validations
                  Callbacks
                  Querying




Saturday, April 2, 2011
Models



         ActiveRecord::Base
       class Product < ActiveRecord::Base
         ...                                products
       end
                                            name    string


                                             sku    string


                                            price   decimal




Saturday, April 2, 2011
Models ➤ Associations
       # manufacturer                                       ingredients
       has_many   :products

       # product
       has_one            :upc
       belongs_to         :manufacturer
       has_many           :batches                batches
       has_many           :ingredients,
                          :through => :batches

       # batch
       belongs_to :product                                    products
       belongs_to :ingredient

       # ingredient
       has_many :batches
       has_many :products,
                :through => :batches               upcs     manufacturers




Saturday, April 2, 2011
Models ➤ Associations

       # create a product and find its manufacturer
       product = manufacturer.products.create({:name => "Kitlifter"})
       product.manufacturer

       # create a upc and find its product's manufacturer
       upc = product.create_upc({:code => "001122"})
       upc.product.manufacturer

       # create a batch (linking a product and ingredient)
       wheat = Ingredient.create({:name => "Wheat"})
       bread = Product.create({:name => "Bread"})

       batch.create({:product => bread, :ingredient => wheat})




Saturday, April 2, 2011
Models ➤ Associations


                                          When should I use has_one
                                          and belongs_to?



                          “Using has_many or belongs_to is more than
                          just on which table the foreign key is placed,
                            itʼs a matter of who can be thought of as
                          ʻowningʼ the other. A product ʻownsʼ a UPC.”




Saturday, April 2, 2011
Models ➤ Validations

     class Product < ActiveRecord::Base
       validates_presence_of   :name
       validates_uniqueness_of :name
       validates_format_of     :sku, :with => /^SKUd{8}$/
       validates_inclusion_of :usda_rating, :in => %w( prime choice )

          validate :cannot_be_active_if_recalled

       def cannot_be_active_if_recalled
         if recalled? && recalled_on < Date.today
         errors.add(:active, "Can't be active if it's been recalled")
       end
     end




Saturday, April 2, 2011
Models ➤ Validations

                                     I know my record is
                                     technically invalid, but
                                     I want to save it anyhow.



                          “It is possible to save a record,
                             without validating, by using
                            save(:validate => false)”




Saturday, April 2, 2011
Models ➤ Callbacks

   class Ingredient
                                                             Callback
        before_destroy    :determine_destroyability           Chain
        before_create     :format_legacy_name
        after_update      :log_changes
        after_create      :import_harvest_data
                                                      determine_destroyability
        #    validation
        #    create
        #    save
        #    update
        #    destroy

   end
                                                        STOP!!




Saturday, April 2, 2011
Models ➤ Querying

       Product.find(98)
       Product.find_by_name("Diet Coke")
       Product.find_by_name_and_sku("Diet Coke", "SKU44387")
       Product.find([98,11,39])
       Product.first
       Product.last
       Product.all
       Product.count

       # old and busted
       Product.find(:all, :conditions => {:name => "Cheese-it!"})

       # new hotness
       Product.where(:name => "Cheese-it!").all




Saturday, April 2, 2011
Models ➤ Querying
       Product.where("name = ?", 'Skittles')
       Product.where(:created_at => Date.yesterday..Date.today)
       Product.where(:sku => ["SKU912", "SKU187", "SKU577"])

       Product.order('name DESC')

       Product.select('id, name')

       Product.limit(5)

       # chainable
       Product.where(:created_at => Date.yesterday..Date.today)
              .limit(10)

       Product.order('created_at ASC').limit(20).offset(40)

       Product.select('created_at').where(:name => 'Twix')




Saturday, April 2, 2011
Models ➤ Querying
     manufacturer.includes(:products)
                 .where('products.usda_rating = ?', 'prime')

     manufacturer.includes(:products)
                 .where(:state => 'AZ')
                 .order('created_at')

     manufacturer.includes(:products => :ingredients)
                 .where('ingredients.name = ?', 'glucose')
                 .order('updated_at')

     manufacturer.joins(:products)
                 .where('products.sku = ?', 'SKU456')

     ingredient.includes(:products => {:manufacturer => :conglomerate})
               .where('conglomerates.name = ?', 'nestle')

     animalia.includes(:phylum => {:class => {:order => {:family => :genus}}})

     child.includes(:parent => [:brother, {:sister => :children}])




Saturday, April 2, 2011
Models ➤ Validations


                                      Why would I use joins
                                      instead of includes?



                             “Using includes will load the
                          records into memory when the query
                              is executing, joins will not.”




Saturday, April 2, 2011
Controllers

                  Routing
                  Filters
                  Conventions




Saturday, April 2, 2011
Controllers ➤ Routing
      resources :products
      # GET /products            =>   index action
      # GET /products/new        =>   new action
      # GET /products/:id        =>   show action
      # GET /products/:id/edit   =>   edit action
      #
      # POST /products           => create action
      #
      # PUT /products/:id        => update action
      #
      # DELETE /products/:id     => destroy action

      products_path # /products
      products_url # http://www.example.com/products

      product_path(@product) # /products/29
      product_path(@product, :xml) # /products/29.xml




Saturday, April 2, 2011
Controllers ➤ Routing
      namespace :admin do
        resources :users
        resources :orders
      end

      admin_users_path # /admin/users
      edit_admin_order_path # /admin/orders/4/edit

      class Admin::UsersController < ApplicationController
        # /app/controllers/admin/users_controller.rb
        # /app/views/admin/users/
      end




Saturday, April 2, 2011
Controllers ➤ Routing
    resources :accounts, :except => :destroy do
      resources :users do
        post :activate, :on => :member
        collection do
          get 'newest'
        end
      end

      resources :clients, :only => [:index, :show]
    end

    account_users_path(@account) # /accounts/182/users
    newest_account_users_path(@account) # /accounts/182/users/newest
    activate_account_user_path(@account, @user) # /accounts/182/user/941

    accounts_clients_path(@account) # /accounts/182/clients
    new_accounts_client_path(@account) # FAIL!




Saturday, April 2, 2011
Controllers ➤ Filters
    class UsersController < ApplicationController
      before_filter :load_manufacturer
      before_filter :find_geo_data, :only => [:show]
      skip_before_filter :require_login

      after_filter :log_access
    end

    # in ApplicationController
    def log_access
      Rails.logger.info("[Access Log] Users Controller access at #{Time.now}")
    end




Saturday, April 2, 2011
Controllers ➤ Conventions
          class ProductsController < ApplicationController
            def index
              # GET /products
            end                                              def update
             def show
               # GET /products/:id
             end
                                                         ☹     # ... update occurred
                                                               @parent.children.each ...
                                                             end
             def new
               # GET /products/new
             end
                                                      def edit
             def create                                 @product = Product.find(params[:id])
               # POST /products                       end


                                               ☹
             end
                                                      def show
             def edit                                   @product = Product.find(params[:id])
               # GET /products/:id/edit
                                                      end
             end
                                                      def destroy
             def update
               # PUT /products/:id                      @product = Product.find(params[:id])
             end                                      end

            def destroy
              # DELETE /products/:id
            end
          end
                                              ☺       before_filter :load_product




Saturday, April 2, 2011
Controllers ➤ Conventions
          class ProductsController < ApplicationController
            def index
              # GET /products
            end
                                                               def update

                                                           ☹
             def show
               # GET /products/:id
                                                                 # ... update occurred
               # renders /app/views/products/show.format         @parent.children.each ...
             end                                               end
             def new
               # GET /products/new
             end
                                                       def edit
             def create                                  @product = Product.find(params[:id])
               # POST /products                        end


                                                ☹
               redirect_to products_url
             end                                       def show
                                                         @product = Product.find(params[:id])
             def edit
                                                       end
               # GET /products/:id/edit
             end
                                                       def destroy
             def update                                  @product = Product.find(params[:id])
               # PUT /products/:id                     end
             end

            def destroy
              # DELETE /products/:id
            end
                                               ☺       before_filter :load_product


          end




Saturday, April 2, 2011
Views

                  Layouts & Helpers
                  Forms
                  Partials
                  ActionView Helpers




Saturday, April 2, 2011
Views ➤ Layouts & Helpers

     def show
       @product = Product.find(params[:id])
     end                                      M   C
     <!-- app/views/products/show.html.erb -->
     <h2><%= @product.name %></h2>

                                                  V
     <p>Price: <%= @product.price %></p>

     <!-- app/layouts/application.html.erb -->
     <div id="container">
       <%= yield %>
     </div>

     <div id="container">
       <h2>Pop-Tarts</h2>
       <p>Price: $3.99</p>
     </div>




Saturday, April 2, 2011
Views ➤ Layouts & Helpers
 <h2><%= @product.name %></h2>
 <p>Price: <%= number_to_currency(@product.price) %></p>
 <p>Ingredients: <%= @product.ingredients.present? ? @product.ingredients.map(&:name).join(',') : 'N/A' %></p>




 # app/helpers/products_helper.rb
 def display_ingredients(ingredients)
   return "N/A" if ingredients.blank?
   ingredients.map(&:name).join(',')
 end



 <h2><%= @product.name %></h2>
 <p>Price: <%= number_to_currency(@product.price) %></p>
 <p>Ingredients: <%= display_ingredients(@product.ingredients) %></p>




Saturday, April 2, 2011
Views ➤ Forms
      <%= form_tag search_path do %>
        <p>
          <%= text_field_tag 'q' %><br />
          <%= submit_tag('Search') %>
        </p>
      <% end %>

      <form action="/search" method="post">
        <p>
          <input type="text" name="q" value="" id="q" />
          <input type="submit" name="commit_search" value="Search" id="commit_search" />
        </p>
      </form>




Saturday, April 2, 2011
Views ➤ Forms
     <h2>New Product</h2>
     <%= form_for(@product) do |f| %>
       <!-- action => /products/:id -->
       <!-- method => POST -->
                                           ← New Record
       <p>
         <%= f.text_field :name %>
       </p>
       <p>
         <%= f.check_box :active %>       <h2>Edit Product</h2>
       </p>                               <%= form_for(@product) do |f| %>
     <% end %>                              <!-- action => /products/:id -->
                                            <!-- method => PUT -->

                                            <p>
                                              <%= f.text_field :name %>
               Existing Record →            </p>
                                            <p>
                                              <%= f.check_box :active %>
                                            </p>
                                          <% end %>




Saturday, April 2, 2011
Views ➤ Forms

      <%=       f.hidden_field :secret %>
      <%=       f.password_field :password %>
      <%=       f.label :name, "Product Name" %>
      <%=       f.radio_button :style, 'Clear' %>
      <%=       f.text_area, :description %>
      <%=       f.select :condition, ["Good", "Fair", "Bad"] %>

      <%= f.email_field :user_email %>
      <%= f.telephone_field :cell_number %>




Saturday, April 2, 2011
Views ➤ Partials
      <% @products.each do |product| %>
        <tr><td><%= link_to(product.title, product_path(product)) %></td></tr>
      <% end %>

      <% @products.each do |product| %>
        <%= render :partial => 'product_row', :locals => {:product => product} %>
      <% end %>



      <!-- app/views/products/_product_row.html.erb -->
      <tr><td><%= link_to(product.title, product_path(product)) %></td></tr>

      <%= render :partial => 'product_row', :collection => @products, :as => :product %>




Saturday, April 2, 2011
Views ➤ Partials
      <!-- app/views/shared/_recent_changes.html.erb -->
      <ul>
        <li>...</li>
        <li>...</li>
      </ul>

      <!-- app/views/reports/index.html.erb -->
      <%= render :partial => 'shared/recent_changes' %>

      <!-- app/views/pages/news.html.erb -->
      <%= render :partial => 'shared/recent_changes' %>



      <%= render :partial => @product %>
      <%= render(@product) %>

      <%= render 'bio', :person => @john   %>




Saturday, April 2, 2011
Views ➤ Partials

                  NumberHelper
                  TextHelper
                  FormHelper
                  JavaScriptHelper
                  DateHelper
                  UrlHelper
                  CaptureHelper
                  SanitizeHelper




Saturday, April 2, 2011
Deploying & Optimizing



                  Heroku
                  Passenger
                  NewRelic

Saturday, April 2, 2011
Resources for Learning
                  Video
                          PeepCode
                          RailsCasts
                          CodeSchool
                  Books
                          The Rails Way
                          Beginning Ruby
                    Ruby for _________
                  Other
                          PHX Rails User Group
                          Gangplank



Saturday, April 2, 2011
@claytonlz
   http://spkr8.com/t/7007

Saturday, April 2, 2011

More Related Content

Viewers also liked

Ruby on Rails Kickstart 103 & 104
Ruby on Rails Kickstart 103 & 104Ruby on Rails Kickstart 103 & 104
Ruby on Rails Kickstart 103 & 104Heng-Yi Wu
 
Ruby on Rails Training - Module 1
Ruby on Rails Training - Module 1Ruby on Rails Training - Module 1
Ruby on Rails Training - Module 1Mark Menard
 
Rails Text Mate Cheats
Rails Text Mate CheatsRails Text Mate Cheats
Rails Text Mate Cheatsdezarrolla
 
Rails 3 generators
Rails 3 generatorsRails 3 generators
Rails 3 generatorsjoshsmoore
 
Railsguide
RailsguideRailsguide
Railsguidelanlau
 
Rails 3 Beginner to Builder 2011 Week 3
Rails 3 Beginner to Builder 2011 Week 3Rails 3 Beginner to Builder 2011 Week 3
Rails 3 Beginner to Builder 2011 Week 3Richard Schneeman
 
Introducing Command Line Applications with Ruby
Introducing Command Line Applications with RubyIntroducing Command Line Applications with Ruby
Introducing Command Line Applications with RubyNikhil Mungel
 
Ruby on Rails 101 - Presentation Slides for a Five Day Introductory Course
Ruby on Rails 101 - Presentation Slides for a Five Day Introductory CourseRuby on Rails 101 - Presentation Slides for a Five Day Introductory Course
Ruby on Rails 101 - Presentation Slides for a Five Day Introductory Coursepeter_marklund
 

Viewers also liked (11)

Ruby on Rails Kickstart 103 & 104
Ruby on Rails Kickstart 103 & 104Ruby on Rails Kickstart 103 & 104
Ruby on Rails Kickstart 103 & 104
 
Ruby on Rails Training - Module 1
Ruby on Rails Training - Module 1Ruby on Rails Training - Module 1
Ruby on Rails Training - Module 1
 
Rails01
Rails01Rails01
Rails01
 
Rest and Rails
Rest and RailsRest and Rails
Rest and Rails
 
Rails Text Mate Cheats
Rails Text Mate CheatsRails Text Mate Cheats
Rails Text Mate Cheats
 
Rails 3 generators
Rails 3 generatorsRails 3 generators
Rails 3 generators
 
Railsguide
RailsguideRailsguide
Railsguide
 
Rails 3 Beginner to Builder 2011 Week 3
Rails 3 Beginner to Builder 2011 Week 3Rails 3 Beginner to Builder 2011 Week 3
Rails 3 Beginner to Builder 2011 Week 3
 
Introducing Command Line Applications with Ruby
Introducing Command Line Applications with RubyIntroducing Command Line Applications with Ruby
Introducing Command Line Applications with Ruby
 
Ruby on Rails 101 - Presentation Slides for a Five Day Introductory Course
Ruby on Rails 101 - Presentation Slides for a Five Day Introductory CourseRuby on Rails 101 - Presentation Slides for a Five Day Introductory Course
Ruby on Rails 101 - Presentation Slides for a Five Day Introductory Course
 
Ruby on Rails for beginners
Ruby on Rails for beginnersRuby on Rails for beginners
Ruby on Rails for beginners
 

Similar to Ruby on Rails 101

Implementing Quality on Java projects
Implementing Quality on Java projectsImplementing Quality on Java projects
Implementing Quality on Java projectsVincent Massol
 
잘 알려지지 않은 Php 코드 활용하기
잘 알려지지 않은 Php 코드 활용하기잘 알려지지 않은 Php 코드 활용하기
잘 알려지지 않은 Php 코드 활용하기형우 안
 
Workshop quality assurance for php projects tek12
Workshop quality assurance for php projects tek12Workshop quality assurance for php projects tek12
Workshop quality assurance for php projects tek12Michelangelo van Dam
 
Magento Imagine eCommerce Conference - February 2011 - Unit Testing with Magento
Magento Imagine eCommerce Conference - February 2011 - Unit Testing with MagentoMagento Imagine eCommerce Conference - February 2011 - Unit Testing with Magento
Magento Imagine eCommerce Conference - February 2011 - Unit Testing with Magentovarien
 
Magento's Imagine eCommerce Conference 2011 - Unit Testing with Magento
Magento's Imagine eCommerce Conference 2011 - Unit Testing with MagentoMagento's Imagine eCommerce Conference 2011 - Unit Testing with Magento
Magento's Imagine eCommerce Conference 2011 - Unit Testing with MagentoMagentoImagine
 
international PHP2011_ilia alshanetsky_Hidden Features of PHP
international PHP2011_ilia alshanetsky_Hidden Features of PHPinternational PHP2011_ilia alshanetsky_Hidden Features of PHP
international PHP2011_ilia alshanetsky_Hidden Features of PHPsmueller_sandsmedia
 
Workshop quality assurance for php projects - phpbelfast
Workshop quality assurance for php projects - phpbelfastWorkshop quality assurance for php projects - phpbelfast
Workshop quality assurance for php projects - phpbelfastMichelangelo van Dam
 
Workshop quality assurance for php projects - ZendCon 2013
Workshop quality assurance for php projects - ZendCon 2013Workshop quality assurance for php projects - ZendCon 2013
Workshop quality assurance for php projects - ZendCon 2013Michelangelo van Dam
 
Quality Assurance for PHP projects - ZendCon 2012
Quality Assurance for PHP projects - ZendCon 2012Quality Assurance for PHP projects - ZendCon 2012
Quality Assurance for PHP projects - ZendCon 2012Michelangelo van Dam
 
Unit Testing in SilverStripe
Unit Testing in SilverStripeUnit Testing in SilverStripe
Unit Testing in SilverStripeIngo Schommer
 
Puppet At Twitter - Puppet Camp Silicon Valley
Puppet At Twitter - Puppet Camp Silicon ValleyPuppet At Twitter - Puppet Camp Silicon Valley
Puppet At Twitter - Puppet Camp Silicon ValleyPuppet
 
Vtlib 1.1
Vtlib 1.1Vtlib 1.1
Vtlib 1.1Arun n
 
Object identification and its management
Object identification and its managementObject identification and its management
Object identification and its managementVinay Kumar Pulabaigari
 
Property Based Testing in PHP
Property Based Testing in PHPProperty Based Testing in PHP
Property Based Testing in PHPvinaikopp
 
Implement rich snippets in your webshop
Implement rich snippets in your webshopImplement rich snippets in your webshop
Implement rich snippets in your webshopArjen Miedema
 
Tips On Trick Odoo Add-On.pptx
Tips On Trick Odoo Add-On.pptxTips On Trick Odoo Add-On.pptx
Tips On Trick Odoo Add-On.pptxAgusto Sipahutar
 
Getting Started with Selenium
Getting Started with SeleniumGetting Started with Selenium
Getting Started with SeleniumDave Haeffner
 
Making Magento flying like a rocket! (A set of valuable tips for developers)
Making Magento flying like a rocket! (A set of valuable tips for developers)Making Magento flying like a rocket! (A set of valuable tips for developers)
Making Magento flying like a rocket! (A set of valuable tips for developers)Ivan Chepurnyi
 
Writing maintainable Oracle PL/SQL code
Writing maintainable Oracle PL/SQL codeWriting maintainable Oracle PL/SQL code
Writing maintainable Oracle PL/SQL codeDonald Bales
 

Similar to Ruby on Rails 101 (20)

Implementing Quality on Java projects
Implementing Quality on Java projectsImplementing Quality on Java projects
Implementing Quality on Java projects
 
잘 알려지지 않은 Php 코드 활용하기
잘 알려지지 않은 Php 코드 활용하기잘 알려지지 않은 Php 코드 활용하기
잘 알려지지 않은 Php 코드 활용하기
 
Workshop quality assurance for php projects tek12
Workshop quality assurance for php projects tek12Workshop quality assurance for php projects tek12
Workshop quality assurance for php projects tek12
 
Magento Imagine eCommerce Conference - February 2011 - Unit Testing with Magento
Magento Imagine eCommerce Conference - February 2011 - Unit Testing with MagentoMagento Imagine eCommerce Conference - February 2011 - Unit Testing with Magento
Magento Imagine eCommerce Conference - February 2011 - Unit Testing with Magento
 
Magento's Imagine eCommerce Conference 2011 - Unit Testing with Magento
Magento's Imagine eCommerce Conference 2011 - Unit Testing with MagentoMagento's Imagine eCommerce Conference 2011 - Unit Testing with Magento
Magento's Imagine eCommerce Conference 2011 - Unit Testing with Magento
 
international PHP2011_ilia alshanetsky_Hidden Features of PHP
international PHP2011_ilia alshanetsky_Hidden Features of PHPinternational PHP2011_ilia alshanetsky_Hidden Features of PHP
international PHP2011_ilia alshanetsky_Hidden Features of PHP
 
Workshop quality assurance for php projects - phpbelfast
Workshop quality assurance for php projects - phpbelfastWorkshop quality assurance for php projects - phpbelfast
Workshop quality assurance for php projects - phpbelfast
 
Workshop quality assurance for php projects - ZendCon 2013
Workshop quality assurance for php projects - ZendCon 2013Workshop quality assurance for php projects - ZendCon 2013
Workshop quality assurance for php projects - ZendCon 2013
 
Quality Assurance for PHP projects - ZendCon 2012
Quality Assurance for PHP projects - ZendCon 2012Quality Assurance for PHP projects - ZendCon 2012
Quality Assurance for PHP projects - ZendCon 2012
 
Unit Testing in SilverStripe
Unit Testing in SilverStripeUnit Testing in SilverStripe
Unit Testing in SilverStripe
 
Ant, Maven and Jenkins
Ant, Maven and JenkinsAnt, Maven and Jenkins
Ant, Maven and Jenkins
 
Puppet At Twitter - Puppet Camp Silicon Valley
Puppet At Twitter - Puppet Camp Silicon ValleyPuppet At Twitter - Puppet Camp Silicon Valley
Puppet At Twitter - Puppet Camp Silicon Valley
 
Vtlib 1.1
Vtlib 1.1Vtlib 1.1
Vtlib 1.1
 
Object identification and its management
Object identification and its managementObject identification and its management
Object identification and its management
 
Property Based Testing in PHP
Property Based Testing in PHPProperty Based Testing in PHP
Property Based Testing in PHP
 
Implement rich snippets in your webshop
Implement rich snippets in your webshopImplement rich snippets in your webshop
Implement rich snippets in your webshop
 
Tips On Trick Odoo Add-On.pptx
Tips On Trick Odoo Add-On.pptxTips On Trick Odoo Add-On.pptx
Tips On Trick Odoo Add-On.pptx
 
Getting Started with Selenium
Getting Started with SeleniumGetting Started with Selenium
Getting Started with Selenium
 
Making Magento flying like a rocket! (A set of valuable tips for developers)
Making Magento flying like a rocket! (A set of valuable tips for developers)Making Magento flying like a rocket! (A set of valuable tips for developers)
Making Magento flying like a rocket! (A set of valuable tips for developers)
 
Writing maintainable Oracle PL/SQL code
Writing maintainable Oracle PL/SQL codeWriting maintainable Oracle PL/SQL code
Writing maintainable Oracle PL/SQL code
 

Recently uploaded

The Role of FIDO in a Cyber Secure Netherlands: FIDO Paris Seminar.pptx
The Role of FIDO in a Cyber Secure Netherlands: FIDO Paris Seminar.pptxThe Role of FIDO in a Cyber Secure Netherlands: FIDO Paris Seminar.pptx
The Role of FIDO in a Cyber Secure Netherlands: FIDO Paris Seminar.pptxLoriGlavin3
 
Dev Dives: Streamline document processing with UiPath Studio Web
Dev Dives: Streamline document processing with UiPath Studio WebDev Dives: Streamline document processing with UiPath Studio Web
Dev Dives: Streamline document processing with UiPath Studio WebUiPathCommunity
 
DevEX - reference for building teams, processes, and platforms
DevEX - reference for building teams, processes, and platformsDevEX - reference for building teams, processes, and platforms
DevEX - reference for building teams, processes, and platformsSergiu Bodiu
 
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek SchlawackFwdays
 
What is DBT - The Ultimate Data Build Tool.pdf
What is DBT - The Ultimate Data Build Tool.pdfWhat is DBT - The Ultimate Data Build Tool.pdf
What is DBT - The Ultimate Data Build Tool.pdfMounikaPolabathina
 
The Ultimate Guide to Choosing WordPress Pros and Cons
The Ultimate Guide to Choosing WordPress Pros and ConsThe Ultimate Guide to Choosing WordPress Pros and Cons
The Ultimate Guide to Choosing WordPress Pros and ConsPixlogix Infotech
 
Advanced Computer Architecture – An Introduction
Advanced Computer Architecture – An IntroductionAdvanced Computer Architecture – An Introduction
Advanced Computer Architecture – An IntroductionDilum Bandara
 
A Journey Into the Emotions of Software Developers
A Journey Into the Emotions of Software DevelopersA Journey Into the Emotions of Software Developers
A Journey Into the Emotions of Software DevelopersNicole Novielli
 
DevoxxFR 2024 Reproducible Builds with Apache Maven
DevoxxFR 2024 Reproducible Builds with Apache MavenDevoxxFR 2024 Reproducible Builds with Apache Maven
DevoxxFR 2024 Reproducible Builds with Apache MavenHervé Boutemy
 
Take control of your SAP testing with UiPath Test Suite
Take control of your SAP testing with UiPath Test SuiteTake control of your SAP testing with UiPath Test Suite
Take control of your SAP testing with UiPath Test SuiteDianaGray10
 
unit 4 immunoblotting technique complete.pptx
unit 4 immunoblotting technique complete.pptxunit 4 immunoblotting technique complete.pptx
unit 4 immunoblotting technique complete.pptxBkGupta21
 
Merck Moving Beyond Passwords: FIDO Paris Seminar.pptx
Merck Moving Beyond Passwords: FIDO Paris Seminar.pptxMerck Moving Beyond Passwords: FIDO Paris Seminar.pptx
Merck Moving Beyond Passwords: FIDO Paris Seminar.pptxLoriGlavin3
 
A Deep Dive on Passkeys: FIDO Paris Seminar.pptx
A Deep Dive on Passkeys: FIDO Paris Seminar.pptxA Deep Dive on Passkeys: FIDO Paris Seminar.pptx
A Deep Dive on Passkeys: FIDO Paris Seminar.pptxLoriGlavin3
 
What is Artificial Intelligence?????????
What is Artificial Intelligence?????????What is Artificial Intelligence?????????
What is Artificial Intelligence?????????blackmambaettijean
 
"Debugging python applications inside k8s environment", Andrii Soldatenko
"Debugging python applications inside k8s environment", Andrii Soldatenko"Debugging python applications inside k8s environment", Andrii Soldatenko
"Debugging python applications inside k8s environment", Andrii SoldatenkoFwdays
 
The Fit for Passkeys for Employee and Consumer Sign-ins: FIDO Paris Seminar.pptx
The Fit for Passkeys for Employee and Consumer Sign-ins: FIDO Paris Seminar.pptxThe Fit for Passkeys for Employee and Consumer Sign-ins: FIDO Paris Seminar.pptx
The Fit for Passkeys for Employee and Consumer Sign-ins: FIDO Paris Seminar.pptxLoriGlavin3
 
Passkey Providers and Enabling Portability: FIDO Paris Seminar.pptx
Passkey Providers and Enabling Portability: FIDO Paris Seminar.pptxPasskey Providers and Enabling Portability: FIDO Paris Seminar.pptx
Passkey Providers and Enabling Portability: FIDO Paris Seminar.pptxLoriGlavin3
 
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)Mark Simos
 
From Family Reminiscence to Scholarly Archive .
From Family Reminiscence to Scholarly Archive .From Family Reminiscence to Scholarly Archive .
From Family Reminiscence to Scholarly Archive .Alan Dix
 
Time Series Foundation Models - current state and future directions
Time Series Foundation Models - current state and future directionsTime Series Foundation Models - current state and future directions
Time Series Foundation Models - current state and future directionsNathaniel Shimoni
 

Recently uploaded (20)

The Role of FIDO in a Cyber Secure Netherlands: FIDO Paris Seminar.pptx
The Role of FIDO in a Cyber Secure Netherlands: FIDO Paris Seminar.pptxThe Role of FIDO in a Cyber Secure Netherlands: FIDO Paris Seminar.pptx
The Role of FIDO in a Cyber Secure Netherlands: FIDO Paris Seminar.pptx
 
Dev Dives: Streamline document processing with UiPath Studio Web
Dev Dives: Streamline document processing with UiPath Studio WebDev Dives: Streamline document processing with UiPath Studio Web
Dev Dives: Streamline document processing with UiPath Studio Web
 
DevEX - reference for building teams, processes, and platforms
DevEX - reference for building teams, processes, and platformsDevEX - reference for building teams, processes, and platforms
DevEX - reference for building teams, processes, and platforms
 
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
 
What is DBT - The Ultimate Data Build Tool.pdf
What is DBT - The Ultimate Data Build Tool.pdfWhat is DBT - The Ultimate Data Build Tool.pdf
What is DBT - The Ultimate Data Build Tool.pdf
 
The Ultimate Guide to Choosing WordPress Pros and Cons
The Ultimate Guide to Choosing WordPress Pros and ConsThe Ultimate Guide to Choosing WordPress Pros and Cons
The Ultimate Guide to Choosing WordPress Pros and Cons
 
Advanced Computer Architecture – An Introduction
Advanced Computer Architecture – An IntroductionAdvanced Computer Architecture – An Introduction
Advanced Computer Architecture – An Introduction
 
A Journey Into the Emotions of Software Developers
A Journey Into the Emotions of Software DevelopersA Journey Into the Emotions of Software Developers
A Journey Into the Emotions of Software Developers
 
DevoxxFR 2024 Reproducible Builds with Apache Maven
DevoxxFR 2024 Reproducible Builds with Apache MavenDevoxxFR 2024 Reproducible Builds with Apache Maven
DevoxxFR 2024 Reproducible Builds with Apache Maven
 
Take control of your SAP testing with UiPath Test Suite
Take control of your SAP testing with UiPath Test SuiteTake control of your SAP testing with UiPath Test Suite
Take control of your SAP testing with UiPath Test Suite
 
unit 4 immunoblotting technique complete.pptx
unit 4 immunoblotting technique complete.pptxunit 4 immunoblotting technique complete.pptx
unit 4 immunoblotting technique complete.pptx
 
Merck Moving Beyond Passwords: FIDO Paris Seminar.pptx
Merck Moving Beyond Passwords: FIDO Paris Seminar.pptxMerck Moving Beyond Passwords: FIDO Paris Seminar.pptx
Merck Moving Beyond Passwords: FIDO Paris Seminar.pptx
 
A Deep Dive on Passkeys: FIDO Paris Seminar.pptx
A Deep Dive on Passkeys: FIDO Paris Seminar.pptxA Deep Dive on Passkeys: FIDO Paris Seminar.pptx
A Deep Dive on Passkeys: FIDO Paris Seminar.pptx
 
What is Artificial Intelligence?????????
What is Artificial Intelligence?????????What is Artificial Intelligence?????????
What is Artificial Intelligence?????????
 
"Debugging python applications inside k8s environment", Andrii Soldatenko
"Debugging python applications inside k8s environment", Andrii Soldatenko"Debugging python applications inside k8s environment", Andrii Soldatenko
"Debugging python applications inside k8s environment", Andrii Soldatenko
 
The Fit for Passkeys for Employee and Consumer Sign-ins: FIDO Paris Seminar.pptx
The Fit for Passkeys for Employee and Consumer Sign-ins: FIDO Paris Seminar.pptxThe Fit for Passkeys for Employee and Consumer Sign-ins: FIDO Paris Seminar.pptx
The Fit for Passkeys for Employee and Consumer Sign-ins: FIDO Paris Seminar.pptx
 
Passkey Providers and Enabling Portability: FIDO Paris Seminar.pptx
Passkey Providers and Enabling Portability: FIDO Paris Seminar.pptxPasskey Providers and Enabling Portability: FIDO Paris Seminar.pptx
Passkey Providers and Enabling Portability: FIDO Paris Seminar.pptx
 
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
 
From Family Reminiscence to Scholarly Archive .
From Family Reminiscence to Scholarly Archive .From Family Reminiscence to Scholarly Archive .
From Family Reminiscence to Scholarly Archive .
 
Time Series Foundation Models - current state and future directions
Time Series Foundation Models - current state and future directionsTime Series Foundation Models - current state and future directions
Time Series Foundation Models - current state and future directions
 

Ruby on Rails 101

  • 1. 101 1.9.2 Ruby on 3.0.5 Rails @claytonlz - Desert Code Camp 2011.1 - http://spkr8.com/t/7007 Saturday, April 2, 2011
  • 2. Ecosystem Models Controllers Views Deploying & Optimizing Resources for Learning Saturday, April 2, 2011
  • 4. “This sure is a nice fork, I bet I could… HOLY SHIT A KNIFE!” Saturday, April 2, 2011
  • 6. “I flippin’ told you MVC is the only way to build web apps! Teach you to doubt DHH!” Saturday, April 2, 2011
  • 8. “These goats are okay, but I really need a yak for some quality shaving” Saturday, April 2, 2011
  • 9. Ecosystem Models Controllers Views Deploying Resources for Learning Saturday, April 2, 2011
  • 10. Models Associations Validations Callbacks Querying Saturday, April 2, 2011
  • 11. Models ActiveRecord::Base class Product < ActiveRecord::Base ... products end name string sku string price decimal Saturday, April 2, 2011
  • 12. Models ➤ Associations # manufacturer ingredients has_many :products # product has_one :upc belongs_to :manufacturer has_many :batches batches has_many :ingredients, :through => :batches # batch belongs_to :product products belongs_to :ingredient # ingredient has_many :batches has_many :products, :through => :batches upcs manufacturers Saturday, April 2, 2011
  • 13. Models ➤ Associations # create a product and find its manufacturer product = manufacturer.products.create({:name => "Kitlifter"}) product.manufacturer # create a upc and find its product's manufacturer upc = product.create_upc({:code => "001122"}) upc.product.manufacturer # create a batch (linking a product and ingredient) wheat = Ingredient.create({:name => "Wheat"}) bread = Product.create({:name => "Bread"}) batch.create({:product => bread, :ingredient => wheat}) Saturday, April 2, 2011
  • 14. Models ➤ Associations When should I use has_one and belongs_to? “Using has_many or belongs_to is more than just on which table the foreign key is placed, itʼs a matter of who can be thought of as ʻowningʼ the other. A product ʻownsʼ a UPC.” Saturday, April 2, 2011
  • 15. Models ➤ Validations class Product < ActiveRecord::Base validates_presence_of :name validates_uniqueness_of :name validates_format_of :sku, :with => /^SKUd{8}$/ validates_inclusion_of :usda_rating, :in => %w( prime choice ) validate :cannot_be_active_if_recalled def cannot_be_active_if_recalled if recalled? && recalled_on < Date.today errors.add(:active, "Can't be active if it's been recalled") end end Saturday, April 2, 2011
  • 16. Models ➤ Validations I know my record is technically invalid, but I want to save it anyhow. “It is possible to save a record, without validating, by using save(:validate => false)” Saturday, April 2, 2011
  • 17. Models ➤ Callbacks class Ingredient Callback before_destroy :determine_destroyability Chain before_create :format_legacy_name after_update :log_changes after_create :import_harvest_data determine_destroyability # validation # create # save # update # destroy end STOP!! Saturday, April 2, 2011
  • 18. Models ➤ Querying Product.find(98) Product.find_by_name("Diet Coke") Product.find_by_name_and_sku("Diet Coke", "SKU44387") Product.find([98,11,39]) Product.first Product.last Product.all Product.count # old and busted Product.find(:all, :conditions => {:name => "Cheese-it!"}) # new hotness Product.where(:name => "Cheese-it!").all Saturday, April 2, 2011
  • 19. Models ➤ Querying Product.where("name = ?", 'Skittles') Product.where(:created_at => Date.yesterday..Date.today) Product.where(:sku => ["SKU912", "SKU187", "SKU577"]) Product.order('name DESC') Product.select('id, name') Product.limit(5) # chainable Product.where(:created_at => Date.yesterday..Date.today) .limit(10) Product.order('created_at ASC').limit(20).offset(40) Product.select('created_at').where(:name => 'Twix') Saturday, April 2, 2011
  • 20. Models ➤ Querying manufacturer.includes(:products) .where('products.usda_rating = ?', 'prime') manufacturer.includes(:products) .where(:state => 'AZ') .order('created_at') manufacturer.includes(:products => :ingredients) .where('ingredients.name = ?', 'glucose') .order('updated_at') manufacturer.joins(:products) .where('products.sku = ?', 'SKU456') ingredient.includes(:products => {:manufacturer => :conglomerate}) .where('conglomerates.name = ?', 'nestle') animalia.includes(:phylum => {:class => {:order => {:family => :genus}}}) child.includes(:parent => [:brother, {:sister => :children}]) Saturday, April 2, 2011
  • 21. Models ➤ Validations Why would I use joins instead of includes? “Using includes will load the records into memory when the query is executing, joins will not.” Saturday, April 2, 2011
  • 22. Controllers Routing Filters Conventions Saturday, April 2, 2011
  • 23. Controllers ➤ Routing resources :products # GET /products => index action # GET /products/new => new action # GET /products/:id => show action # GET /products/:id/edit => edit action # # POST /products => create action # # PUT /products/:id => update action # # DELETE /products/:id => destroy action products_path # /products products_url # http://www.example.com/products product_path(@product) # /products/29 product_path(@product, :xml) # /products/29.xml Saturday, April 2, 2011
  • 24. Controllers ➤ Routing namespace :admin do resources :users resources :orders end admin_users_path # /admin/users edit_admin_order_path # /admin/orders/4/edit class Admin::UsersController < ApplicationController # /app/controllers/admin/users_controller.rb # /app/views/admin/users/ end Saturday, April 2, 2011
  • 25. Controllers ➤ Routing resources :accounts, :except => :destroy do resources :users do post :activate, :on => :member collection do get 'newest' end end resources :clients, :only => [:index, :show] end account_users_path(@account) # /accounts/182/users newest_account_users_path(@account) # /accounts/182/users/newest activate_account_user_path(@account, @user) # /accounts/182/user/941 accounts_clients_path(@account) # /accounts/182/clients new_accounts_client_path(@account) # FAIL! Saturday, April 2, 2011
  • 26. Controllers ➤ Filters class UsersController < ApplicationController before_filter :load_manufacturer before_filter :find_geo_data, :only => [:show] skip_before_filter :require_login after_filter :log_access end # in ApplicationController def log_access Rails.logger.info("[Access Log] Users Controller access at #{Time.now}") end Saturday, April 2, 2011
  • 27. Controllers ➤ Conventions class ProductsController < ApplicationController def index # GET /products end def update def show # GET /products/:id end ☹ # ... update occurred @parent.children.each ... end def new # GET /products/new end def edit def create @product = Product.find(params[:id]) # POST /products end ☹ end def show def edit @product = Product.find(params[:id]) # GET /products/:id/edit end end def destroy def update # PUT /products/:id @product = Product.find(params[:id]) end end def destroy # DELETE /products/:id end end ☺ before_filter :load_product Saturday, April 2, 2011
  • 28. Controllers ➤ Conventions class ProductsController < ApplicationController def index # GET /products end def update ☹ def show # GET /products/:id # ... update occurred # renders /app/views/products/show.format @parent.children.each ... end end def new # GET /products/new end def edit def create @product = Product.find(params[:id]) # POST /products end ☹ redirect_to products_url end def show @product = Product.find(params[:id]) def edit end # GET /products/:id/edit end def destroy def update @product = Product.find(params[:id]) # PUT /products/:id end end def destroy # DELETE /products/:id end ☺ before_filter :load_product end Saturday, April 2, 2011
  • 29. Views Layouts & Helpers Forms Partials ActionView Helpers Saturday, April 2, 2011
  • 30. Views ➤ Layouts & Helpers def show @product = Product.find(params[:id]) end M C <!-- app/views/products/show.html.erb --> <h2><%= @product.name %></h2> V <p>Price: <%= @product.price %></p> <!-- app/layouts/application.html.erb --> <div id="container"> <%= yield %> </div> <div id="container"> <h2>Pop-Tarts</h2> <p>Price: $3.99</p> </div> Saturday, April 2, 2011
  • 31. Views ➤ Layouts & Helpers <h2><%= @product.name %></h2> <p>Price: <%= number_to_currency(@product.price) %></p> <p>Ingredients: <%= @product.ingredients.present? ? @product.ingredients.map(&:name).join(',') : 'N/A' %></p> # app/helpers/products_helper.rb def display_ingredients(ingredients) return "N/A" if ingredients.blank? ingredients.map(&:name).join(',') end <h2><%= @product.name %></h2> <p>Price: <%= number_to_currency(@product.price) %></p> <p>Ingredients: <%= display_ingredients(@product.ingredients) %></p> Saturday, April 2, 2011
  • 32. Views ➤ Forms <%= form_tag search_path do %> <p> <%= text_field_tag 'q' %><br /> <%= submit_tag('Search') %> </p> <% end %> <form action="/search" method="post"> <p> <input type="text" name="q" value="" id="q" /> <input type="submit" name="commit_search" value="Search" id="commit_search" /> </p> </form> Saturday, April 2, 2011
  • 33. Views ➤ Forms <h2>New Product</h2> <%= form_for(@product) do |f| %> <!-- action => /products/:id --> <!-- method => POST --> ← New Record <p> <%= f.text_field :name %> </p> <p> <%= f.check_box :active %> <h2>Edit Product</h2> </p> <%= form_for(@product) do |f| %> <% end %> <!-- action => /products/:id --> <!-- method => PUT --> <p> <%= f.text_field :name %> Existing Record → </p> <p> <%= f.check_box :active %> </p> <% end %> Saturday, April 2, 2011
  • 34. Views ➤ Forms <%= f.hidden_field :secret %> <%= f.password_field :password %> <%= f.label :name, "Product Name" %> <%= f.radio_button :style, 'Clear' %> <%= f.text_area, :description %> <%= f.select :condition, ["Good", "Fair", "Bad"] %> <%= f.email_field :user_email %> <%= f.telephone_field :cell_number %> Saturday, April 2, 2011
  • 35. Views ➤ Partials <% @products.each do |product| %> <tr><td><%= link_to(product.title, product_path(product)) %></td></tr> <% end %> <% @products.each do |product| %> <%= render :partial => 'product_row', :locals => {:product => product} %> <% end %> <!-- app/views/products/_product_row.html.erb --> <tr><td><%= link_to(product.title, product_path(product)) %></td></tr> <%= render :partial => 'product_row', :collection => @products, :as => :product %> Saturday, April 2, 2011
  • 36. Views ➤ Partials <!-- app/views/shared/_recent_changes.html.erb --> <ul> <li>...</li> <li>...</li> </ul> <!-- app/views/reports/index.html.erb --> <%= render :partial => 'shared/recent_changes' %> <!-- app/views/pages/news.html.erb --> <%= render :partial => 'shared/recent_changes' %> <%= render :partial => @product %> <%= render(@product) %> <%= render 'bio', :person => @john %> Saturday, April 2, 2011
  • 37. Views ➤ Partials NumberHelper TextHelper FormHelper JavaScriptHelper DateHelper UrlHelper CaptureHelper SanitizeHelper Saturday, April 2, 2011
  • 38. Deploying & Optimizing Heroku Passenger NewRelic Saturday, April 2, 2011
  • 39. Resources for Learning Video PeepCode RailsCasts CodeSchool Books The Rails Way Beginning Ruby Ruby for _________ Other PHX Rails User Group Gangplank Saturday, April 2, 2011
  • 40. @claytonlz http://spkr8.com/t/7007 Saturday, April 2, 2011