SlideShare uma empresa Scribd logo
1 de 46
Baixar para ler offline
Beginner to Builder
                       Week8




July, 2011
Monday, August 8, 11
Rails - Week 8
                       • Dealing with nil
                       • Acceptance Testing
                       • Partials
                       • Cells
                       • Memcache


@Schneems
Monday, August 8, 11
Dealing with Nil
                       user = User.where(:username => "schneems").first
                       #<User ... >
                       user.image_url
                       >> "/schneems.png"

                       user = nil
                       user.image_url
                       # NameError: undefined local variable or method `user'
                       for #<Object:0x1001dc288>




@Schneems
Monday, August 8, 11
try to deal
                       # use try from ActiveSupport
                       user = User.where(:username => "schneems").first
                       #<User ... >
                       user.try(:image_url) || "/not_found.png"
                       >> "/schneems.png"

                       user = nil
                       user.try(:image_url) || "/not_found.png"
                       >> "/not_found.png"




@Schneems
Monday, August 8, 11
|| & ||=
                       per_page = params[:per_page]
                       per_page = 10 if per_page.blank?

                       # instead
                       per_page = params[:per_page]||10

                       # or
                       per_page = params[:per_page]
                       per_page ||= 10




@Schneems
Monday, August 8, 11
‘if’ returns result
                       # if returns to where it was called
                       result = if true
                         "foo"
                       else
                         "bar"
                       end

                       puts result
                       >> "foo"

                       result = if false
                         "foo"
                       else
                         "bar"
                       end

                       puts result
                       >> "bar"
@Schneems
Monday, August 8, 11
Acceptance Testing
                       • Run your full application stack
                       • Behavior Driven Development (BDD)
                         • High payout for little time testing
                         • slow
                         • potentially brittle


@Schneems
Monday, August 8, 11
Capybara & Rspec
                       • Capybara
                         • Headless browser
                         • open your webpages
                         • click links ...
                       Gemfile
                        gem 'capybara', '0.3.7'
                        gem 'rspec-rails', '1.3.2'

@Schneems
Monday, August 8, 11
Capybara & Rspec
                       # go to a path
                       visit root_path
                       visit "/"

                       # click buttons
                       click "sign in"

                       # fill out forms
                       fill_in ‘Email’, :with => "schneems@example.com"




@Schneems
Monday, August 8, 11
Capybara & Rspec
                       http://codingfrontier.com/integration-testing-setup-with-rspec-and-capy
                       /spec/acceptance/signin_spec.rb
                        context "as a guest on the sign in page" do
                          # Generate a valid user
                          let(:user) { Factory(:user) }
                          context ‘with valid credentials’ do
                            #Fill in the form with the user’s credentials and submit it.
                            before do
                              visit root_path
                              click ‘Sign In’
                              fill_in ‘Email’, :with => user.email
                              fill_in ‘Password’, :with => ‘password’
                              click ‘Submit’
                            end

                            it "has a sign out link" do
                              page.should have_xpath(‘//a’, :text => ‘Sign Out’)
                            end

                            it "knows who I am" do
                              page.should have_content(“Welcome, #{user.email}!”)
                            end
                          end
                        end
@Schneems
Monday, August 8, 11
DRY Views
                       •   Helpers
                           •   Small resusable components
                       • content_for
                         • Control page flow of compnents out of
                           normal
                                   placement

                       • Partials
                         • Large reusable components
                       • Cells
                         • type logic is needed when controller
                            Reusable components
@Schneems
Monday, August 8, 11
ViewHelpers
                       • Rails has build in helpers
                         • link_to
                         • image_tag
                         • etc.
                       • Write your Own


@Schneems
Monday, August 8, 11
ViewHelpers
                 app/helpers/product_helper.rb
                   link_to_product(product = nil)
                     link_to image_tag(product.image_url),
                   product_path(product), :class => 'product'
                   end


              app/views/product/index.html.erb
                  <%= link_to_product(@product) %>


                  <a href=“...” class=”product”>
                    <imgr src = “...” />
                  </a>
@Schneems
Monday, August 8, 11
content_for & yield
                       • Replace content using content_for
   <head>
     <title>                             <html>
        <%= yield :head %>                 <head>
     </title>                              <title>A simple page</title>
   </head>                                 </head>
   <p>Hello, Rails!</p>                    <body>
                                    =>     <p>Hello, Rails!</p>
   <% content_for :head do %>              </body>
        A simple page                    </html>
   <% end %>


@Schneems
Monday, August 8, 11
content_for in layouts
                       • use helpers & content_for together
                         in layouts


        <body id="<%= id_for_body(yield(:body_id)) %>"
              class="<%= classes_for_body(yield(:body_class)) %>
              <%= logged_in? ? 'logged-in' : 'not-logged-in' %>">
          <%= yield %>
        </body>




@Schneems
Monday, August 8, 11
content_for in layouts
                       # content_for head
                       <%= yield :head_analytics %>
                       <%= yield :head_stylesheets %>
                       <%= yield :head_scripts %>
                       <%= yield :head %>

                       # content_for body
                       <%= yield :main_title %>
                       <%= yield :sidebar_title %>
                       <%= yield :sidebar %>

                       # content_for footer
                       <%= yield :footer %>
                       <%= yield :footer_libraries %>
                       <%= yield :footer_scripts %>
                       <%= yield :footer_analytics %>

@Schneems
Monday, August 8, 11
Partials
                       • Reusable chunks of view code
                <%#     renders 'spots.html.erb' with @spot %>
                <%=     render :partial => "spot", :object => @spot %>
                <%=     render "spot", :object => @spot %>
                <%=     render @spot %>

                <%# renders 'spots.html.erb' for each spot in @spots %>
                <%= render @spots %>
                <%= render "spot", :collection => @spots %>



@Schneems
Monday, August 8, 11
Partials

                <%# renders 'spots.html.erb' for each spot in @spots %>
                <%= render @spots %>


                /spots/_spots.html.erb
                <div>
                  <h3>Name:</h3>
                  <p><%= spot.name %></p>
                  <p><%= spot.description %></p>
                </div>

@Schneems
Monday, August 8, 11
Partials
                       • Locals
                <%# renders 'spots.html.erb' for each spot in @spots %>
                <%= render @spots, :locals => {:foo => ”bar”} %>


                /spots/_spots.html.erb
                <div>
                  <h3>Name:</h3>
                  <p><%= spot.name %></p>
                  <p><%= spot.description %></p>
                  <p><%= foo %></p>
                </div>
@Schneems
Monday, August 8, 11
Partials
                       • Optional Locals
                <%# renders 'spot.html.erb' for each spot in @spots %>
                <%= render @spot2 %>


                /spots/_spot.html.erb
                <div>
                  <h3>Name:</h3>
                  <p><%= spot.name %></p>
                  <p><%= spot.description %></p>
                  <p><%= local_assigns[:foo]||'something else' %></p>
                </div>
@Schneems
Monday, August 8, 11
Cells
                       • View Components
                       • Look and Feel like Controllers


                         gem install cells



@Schneems
Monday, August 8, 11
Cells
   /app/views/product/index.html
           <div id="header">
             <%= render_cell :cart, :display, :user => @current_user %>

    /app/cells/cart_cell.rb
          class CartCell < Cell::Rails
            def display(options)
              user    = args[:user]
              @items = user.items_in_cart
              render # renders display.html.haml
            end
          end
  /app/cells/cart.display.html.erb
           <p>You have <%= @items.size %></p>
@Schneems
Monday, August 8, 11
DRY Views
                       •   Helpers
                           •   Small resusable components
                       • content_for
                         • Control page flow of compnents out of
                           normal
                                   placement

                       • Partials
                         • Large reusable components
                       • Cells
                         • type logic is needed when controller
                            Reusable components
@Schneems
Monday, August 8, 11
Caching
                       • Store data in alater so it can be
                         served quicker
                                         cache




@Schneems
Monday, August 8, 11
Page Caching
                       • Super Fast
                       • Limited use cases
                       class ProductsController < ActionController
                         caches_page :index

                         def index
                           @products = Products.all
                         end
                       end


                   http://guides.rubyonrails.org/caching_with_rails.html
@Schneems
Monday, August 8, 11
Page Caching
                       class ProductsController < ActionController
                         caches_page :index

                         def index
                           @products = Products.all
                         end

                         def create
                           expire_page :action => :index
                         end
                       end


                   http://guides.rubyonrails.org/caching_with_rails.html
@Schneems
Monday, August 8, 11
Action Caching
                       • Allows Authentication checks
                        class ProductsController < ActionController
                          before_filter :authenticate
                          caches_action :index

                          def index
                            @products = Product.all
                          end

                          def create
                            expire_action :action => :index
                          end
                        end
@Schneems
Monday, August 8, 11
Action Caching
                       • :layout => false
                         • allows dynamic currentthe layout to
                            render such as
                                           info in
                                                   user
                       • :if & :unless
                         •
      caches_action :index, :layout => false
      caches_action :index, :if => lambda {current_user.present?}
      caches_action :index, :unless => lambda {current_user.blank?}



@Schneems
Monday, August 8, 11
Fragment Caching
                       • Cache individual parts of pages
                         <% cache('all_available_products') do %>
                           All available products:
                         <% end %>




@Schneems
Monday, August 8, 11
Fragment Caching
                       • Cache individual parts of pages
                       <% cache(:action => 'recent',
                                 :action_suffix => 'all_products') do %>
                         All available products:
                         ...
                       <%- end -%>




@Schneems
Monday, August 8, 11
Fragment Caching
                       • Expire fragments
     expire_fragment(:controller => 'products',
                      :action => 'recent',
                      :action_suffix => 'all_products')




@Schneems
Monday, August 8, 11
Sweeping Cache
                       class ProductsController < ActionController
                         before_filter :authenticate
                         caches_action :index
                         cache_sweeper :product_sweeper

                         def index
                           @products = Product.all
                         end
                       end



@Schneems
Monday, August 8, 11
Sweeping Cache
     class ProductSweeper < ActionController::Caching::Sweeper
         observe Product # This sweeper is going to keep an eye on the Product model
          # If our sweeper detects that a Product was created call this
         def after_create(product)
                 expire_cache_for(product)
         end


         private
         def expire_cache_for(product)
             # Expire the index page now that we added a new product
             expire_page(:controller => 'products', :action => 'index')
             expire_fragment('all_available_products')
         end
     end
@Schneems
Monday, August 8, 11
Cache Stores
                       • Set the Cache store in your
                         environment

      ActionController::Base.cache_store = :memory_store
      ActionController::Base.cache_store = :drb_store,
                                           "druby://localhost:9192"
      ActionController::Base.cache_store = :mem_cache_store,
                                            "localhost"




@Schneems
Monday, August 8, 11
Cache Stores
                       • Simple Key/Value storage
      Rails.cache.read("city")   # => nil
      Rails.cache.write("city", "Duckburgh")
      Rails.cache.read("city")   # => "Duckburgh"




@Schneems
Monday, August 8, 11
Cache Stores
                       • fetch
      Rails.cache.read("city") # => nil
      Rails.cache.fetch("city") do
        "Duckburgh"
      end
      # => "Duckburgh"
      Rails.cache.read("city") # => "Duckburgh"




@Schneems
Monday, August 8, 11
Cache Stores
                       • Expires_in
      Rails.cache.write("city", "Duckburgh", :expires_in =>
      1.minute)
      Rails.cache.read("city") # => "Duckburgh"
      sleep 120
      Rails.cache.read("city") # => nil




@Schneems
Monday, August 8, 11
Memcache
                       • Cache your rails objects
                       • Memcache Gem
                       • Key Value Store (NOSQL)
                         • Use to cache Expensive Queries
                        require 'memcached'
                        $cache = Memcached.new("localhost:11211")
                        $cache.set("foo", "bar")
                        $cache.get("foo")
                        => "bar"

@Schneems
Monday, August 8, 11
Memcache
                       # store strings
                       $cache.set("key", "value")
                       $cache.get("key")
                       => "bar"

                       # store any ruby object
                       $cache.set("foo", [1,2,3,4,5])
                       $cache.get("foo")
                       => [1,2,3,4,5]

                       # srsly any ruby object
                       $cache.set("foo", User.last)
                       $cache.get("foo")
                       => #< User ... >
@Schneems
Monday, August 8, 11
Memcache

                ActionController::Base.cache_store = :mem_cache_store,
                "localhost"




@Schneems
Monday, August 8, 11
Memcache
                       • Cache frequent queries
             class User < ActiveRecord::Base
               def self.fetch(username)
                 Rails.cache.fetch("user:#{username}") do
                   User.where(:username => "#{username}").first
                 end
               end
             end

             => User.fetch("schneems") #=> #<User id: 263595 ... >


@Schneems
Monday, August 8, 11
Memcache
                       • Cache expensive queries
             class User < ActiveRecord::Base
               def fetch_friends
                 Rails.cache.fetch("users:friends:#{self.id}") do
                   friends = Friendships.where(:user_1_id => self.id)
                 end
               end
             end

                  => User.fetch("schneems").fetch_friend_ids

@Schneems
Monday, August 8, 11
Memcache
                       • Blazing Fast
                       # Database
                         Benchmark.measure do
                           User.where(:username => "schneems").first
                         end.real
                       => 0.09 s

                       # Memcache
                         Benchmark.measure do
                           User.fetch("schneems")
                         end.real
                       => 0.0009 s
@Schneems
Monday, August 8, 11
Memcache
                       • Key Value Store
                       • Holds ruby objects
                       • Extremely fast
                       • volatile
                       • available on Heroku
                       >> heroku addons:add memcache



@Schneems
Monday, August 8, 11
Bonus - Keytar
                       class User < ActiveRecord::Base
                       • includeKeytar to generate Keys
                           Use Keytar
                         define_keys :username, :friends
                       •
                       end Use those keys in Memcache

                       User.username_key("schneems")
                       => "user:username:schneems"
                       user = Rails.cache.fetch(User.username_key("schneems"))
                       => # < User id:33 ... >

                       user.friends_key
                       => "users:friends:33"
                       friends = Rails.cache.fetch(user.friends_key)
                       => #[#< User ... >, #< User ... >, ... ]
@Schneems
Monday, August 8, 11
Questions?
                       http://guides.rubyonrails.org
                        http://stackoverflow.com
                           http://peepcode.com


@Schneems
Monday, August 8, 11

Mais conteúdo relacionado

Mais procurados

Stack Overflow Austin - jQuery for Developers
Stack Overflow Austin - jQuery for DevelopersStack Overflow Austin - jQuery for Developers
Stack Overflow Austin - jQuery for Developers
Jonathan Sharp
 
Introduction To Django (Strange Loop 2011)
Introduction To Django (Strange Loop 2011)Introduction To Django (Strange Loop 2011)
Introduction To Django (Strange Loop 2011)
Jacob Kaplan-Moss
 
10 Things Every Plugin Developer Should Know (WordCamp Atlanta 2013)
10 Things Every Plugin Developer Should Know (WordCamp Atlanta 2013)10 Things Every Plugin Developer Should Know (WordCamp Atlanta 2013)
10 Things Every Plugin Developer Should Know (WordCamp Atlanta 2013)
arcware
 

Mais procurados (20)

Practical HTML5: Using It Today
Practical HTML5: Using It TodayPractical HTML5: Using It Today
Practical HTML5: Using It Today
 
Tips and Tricks for LiveWhale Development
Tips and Tricks for LiveWhale DevelopmentTips and Tricks for LiveWhale Development
Tips and Tricks for LiveWhale Development
 
Assetic (Zendcon)
Assetic (Zendcon)Assetic (Zendcon)
Assetic (Zendcon)
 
You're Doing it Wrong - WordCamp Atlanta
You're Doing it Wrong - WordCamp AtlantaYou're Doing it Wrong - WordCamp Atlanta
You're Doing it Wrong - WordCamp Atlanta
 
Why You Should be Using Web Components Right Now. And How. ForwardJS July 2015
Why You Should be Using Web Components Right Now. And How. ForwardJS July 2015Why You Should be Using Web Components Right Now. And How. ForwardJS July 2015
Why You Should be Using Web Components Right Now. And How. ForwardJS July 2015
 
jQuery UI and Plugins
jQuery UI and PluginsjQuery UI and Plugins
jQuery UI and Plugins
 
Assetic (Symfony Live Paris)
Assetic (Symfony Live Paris)Assetic (Symfony Live Paris)
Assetic (Symfony Live Paris)
 
jQuery Essentials
jQuery EssentialsjQuery Essentials
jQuery Essentials
 
ActiveResource & REST
ActiveResource & RESTActiveResource & REST
ActiveResource & REST
 
jQuery Loves Developers - Oredev 2009
jQuery Loves Developers - Oredev 2009jQuery Loves Developers - Oredev 2009
jQuery Loves Developers - Oredev 2009
 
You're Doing it Wrong - WordCamp Orlando
You're Doing it Wrong - WordCamp OrlandoYou're Doing it Wrong - WordCamp Orlando
You're Doing it Wrong - WordCamp Orlando
 
Stack Overflow Austin - jQuery for Developers
Stack Overflow Austin - jQuery for DevelopersStack Overflow Austin - jQuery for Developers
Stack Overflow Austin - jQuery for Developers
 
Overview of Backbone
Overview of BackboneOverview of Backbone
Overview of Backbone
 
Cucumber
CucumberCucumber
Cucumber
 
Sherlock Markup and Sammy Semantic - drupal theming forensic analysis
Sherlock Markup and Sammy Semantic - drupal theming forensic analysisSherlock Markup and Sammy Semantic - drupal theming forensic analysis
Sherlock Markup and Sammy Semantic - drupal theming forensic analysis
 
How to migrate Cakephp 1.x to 2.x
How to migrate Cakephp 1.x to 2.xHow to migrate Cakephp 1.x to 2.x
How to migrate Cakephp 1.x to 2.x
 
Introduction To Django (Strange Loop 2011)
Introduction To Django (Strange Loop 2011)Introduction To Django (Strange Loop 2011)
Introduction To Django (Strange Loop 2011)
 
jQuery for beginners
jQuery for beginnersjQuery for beginners
jQuery for beginners
 
10 Things Every Plugin Developer Should Know (WordCamp Atlanta 2013)
10 Things Every Plugin Developer Should Know (WordCamp Atlanta 2013)10 Things Every Plugin Developer Should Know (WordCamp Atlanta 2013)
10 Things Every Plugin Developer Should Know (WordCamp Atlanta 2013)
 
Wp meetup custom post types
Wp meetup custom post typesWp meetup custom post types
Wp meetup custom post types
 

Destaque

Programas y políticas de integridad en el ámbito privado. Buenas prácticas en...
Programas y políticas de integridad en el ámbito privado. Buenas prácticas en...Programas y políticas de integridad en el ámbito privado. Buenas prácticas en...
Programas y políticas de integridad en el ámbito privado. Buenas prácticas en...
EUROsociAL II
 
04197201tt
04197201tt04197201tt
04197201tt
Yambal
 
La banca regional en méxico (1870 1930)(sinaloa y veracruz)
La banca regional en méxico (1870 1930)(sinaloa y veracruz)La banca regional en méxico (1870 1930)(sinaloa y veracruz)
La banca regional en méxico (1870 1930)(sinaloa y veracruz)
Pumukel
 
Ciudadanía digital corti gudy nico
Ciudadanía digital corti gudy nicoCiudadanía digital corti gudy nico
Ciudadanía digital corti gudy nico
budicoitanqe
 

Destaque (20)

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
 
UT on Rails3 2010- Week 2
UT on Rails3 2010- Week 2UT on Rails3 2010- Week 2
UT on Rails3 2010- Week 2
 
Rails 3 Beginner to Builder 2011 Week 4
Rails 3 Beginner to Builder 2011 Week 4Rails 3 Beginner to Builder 2011 Week 4
Rails 3 Beginner to Builder 2011 Week 4
 
Rails 3 Beginner to Builder 2011 Week 6
Rails 3 Beginner to Builder 2011 Week 6Rails 3 Beginner to Builder 2011 Week 6
Rails 3 Beginner to Builder 2011 Week 6
 
Rails 3 Beginner to Builder 2011 Week 2
Rails 3 Beginner to Builder 2011 Week 2Rails 3 Beginner to Builder 2011 Week 2
Rails 3 Beginner to Builder 2011 Week 2
 
Rails 3 Beginner to Builder 2011 Week 1
Rails 3 Beginner to Builder 2011 Week 1Rails 3 Beginner to Builder 2011 Week 1
Rails 3 Beginner to Builder 2011 Week 1
 
Programas y políticas de integridad en el ámbito privado. Buenas prácticas en...
Programas y políticas de integridad en el ámbito privado. Buenas prácticas en...Programas y políticas de integridad en el ámbito privado. Buenas prácticas en...
Programas y políticas de integridad en el ámbito privado. Buenas prácticas en...
 
Guía especial de comercio electrónico por www.20minutos.es
Guía especial de comercio electrónico por www.20minutos.esGuía especial de comercio electrónico por www.20minutos.es
Guía especial de comercio electrónico por www.20minutos.es
 
Email Marketing: Curso Paso a Paso para desarrollar una estrategia exitosa
Email Marketing: Curso Paso a Paso para desarrollar una estrategia exitosaEmail Marketing: Curso Paso a Paso para desarrollar una estrategia exitosa
Email Marketing: Curso Paso a Paso para desarrollar una estrategia exitosa
 
Curso sobre Redes Sociales: Construcción de Capital Humano - Dia 1
Curso sobre Redes Sociales: Construcción de Capital Humano - Dia 1Curso sobre Redes Sociales: Construcción de Capital Humano - Dia 1
Curso sobre Redes Sociales: Construcción de Capital Humano - Dia 1
 
Von der Massenkommunikation zur Kommunikation der Massen
Von der Massenkommunikation zur Kommunikation der MassenVon der Massenkommunikation zur Kommunikation der Massen
Von der Massenkommunikation zur Kommunikation der Massen
 
CASOS de PAÍS - Jeanette de Noack ADA- Guatemala
CASOS de PAÍS - Jeanette de Noack ADA- GuatemalaCASOS de PAÍS - Jeanette de Noack ADA- Guatemala
CASOS de PAÍS - Jeanette de Noack ADA- Guatemala
 
Apropiacion
ApropiacionApropiacion
Apropiacion
 
proyecto the news
proyecto the newsproyecto the news
proyecto the news
 
HOLLAND AMERICA LINE - Los Mejores Cruceros Premium
HOLLAND AMERICA LINE - Los Mejores Cruceros PremiumHOLLAND AMERICA LINE - Los Mejores Cruceros Premium
HOLLAND AMERICA LINE - Los Mejores Cruceros Premium
 
04197201tt
04197201tt04197201tt
04197201tt
 
presentacion power point
presentacion power pointpresentacion power point
presentacion power point
 
La banca regional en méxico (1870 1930)(sinaloa y veracruz)
La banca regional en méxico (1870 1930)(sinaloa y veracruz)La banca regional en méxico (1870 1930)(sinaloa y veracruz)
La banca regional en méxico (1870 1930)(sinaloa y veracruz)
 
Ciudadanía digital corti gudy nico
Ciudadanía digital corti gudy nicoCiudadanía digital corti gudy nico
Ciudadanía digital corti gudy nico
 
Version word articulo revista cio
Version word articulo revista cioVersion word articulo revista cio
Version word articulo revista cio
 

Semelhante a Rails 3 Beginner to Builder 2011 Week 8

Be happy with Ruby on Rails - CEUNSP Itu
Be happy with Ruby on Rails - CEUNSP ItuBe happy with Ruby on Rails - CEUNSP Itu
Be happy with Ruby on Rails - CEUNSP Itu
Lucas Renan
 
Desenvolvimento web com Ruby on Rails (parte 2)
Desenvolvimento web com Ruby on Rails (parte 2)Desenvolvimento web com Ruby on Rails (parte 2)
Desenvolvimento web com Ruby on Rails (parte 2)
Joao Lucas Santana
 
Browser Uploads to S3 using HTML POST Forms
Browser Uploads to S3 using HTML POST FormsBrowser Uploads to S3 using HTML POST Forms
Browser Uploads to S3 using HTML POST Forms
Hiroyasu Suzuki
 
Survey of Front End Topics in Rails
Survey of Front End Topics in RailsSurvey of Front End Topics in Rails
Survey of Front End Topics in Rails
Benjamin Vandgrift
 
Simple Web Apps With Sinatra
Simple Web Apps With SinatraSimple Web Apps With Sinatra
Simple Web Apps With Sinatra
a_l
 

Semelhante a Rails 3 Beginner to Builder 2011 Week 8 (20)

Rails 3 Beginner to Builder 2011 Week 5
Rails 3 Beginner to Builder 2011 Week 5Rails 3 Beginner to Builder 2011 Week 5
Rails 3 Beginner to Builder 2011 Week 5
 
Be happy with Ruby on Rails - CEUNSP Itu
Be happy with Ruby on Rails - CEUNSP ItuBe happy with Ruby on Rails - CEUNSP Itu
Be happy with Ruby on Rails - CEUNSP Itu
 
Mojolicious
MojoliciousMojolicious
Mojolicious
 
MongoDB at Sailthru: Scaling and Schema Design
MongoDB at Sailthru: Scaling and Schema DesignMongoDB at Sailthru: Scaling and Schema Design
MongoDB at Sailthru: Scaling and Schema Design
 
Rails ORM De-mystifying Active Record has_many
Rails ORM De-mystifying Active Record has_manyRails ORM De-mystifying Active Record has_many
Rails ORM De-mystifying Active Record has_many
 
Pocket Knife JS
Pocket Knife JSPocket Knife JS
Pocket Knife JS
 
Rails 3 (beta) Roundup
Rails 3 (beta) RoundupRails 3 (beta) Roundup
Rails 3 (beta) Roundup
 
Desenvolvimento web com Ruby on Rails (parte 2)
Desenvolvimento web com Ruby on Rails (parte 2)Desenvolvimento web com Ruby on Rails (parte 2)
Desenvolvimento web com Ruby on Rails (parte 2)
 
Rails Antipatterns | Open Session with Chad Pytel
Rails Antipatterns | Open Session with Chad Pytel Rails Antipatterns | Open Session with Chad Pytel
Rails Antipatterns | Open Session with Chad Pytel
 
Transformando os pepinos do cliente no código de testes da sua aplicação
Transformando os pepinos do cliente no código de testes da sua aplicaçãoTransformando os pepinos do cliente no código de testes da sua aplicação
Transformando os pepinos do cliente no código de testes da sua aplicação
 
Browser Uploads to S3 using HTML POST Forms
Browser Uploads to S3 using HTML POST FormsBrowser Uploads to S3 using HTML POST Forms
Browser Uploads to S3 using HTML POST Forms
 
Survey of Front End Topics in Rails
Survey of Front End Topics in RailsSurvey of Front End Topics in Rails
Survey of Front End Topics in Rails
 
Associations & JavaScript
Associations & JavaScriptAssociations & JavaScript
Associations & JavaScript
 
Be Happy With Ruby on Rails - Ecosystem
Be Happy With Ruby on Rails - EcosystemBe Happy With Ruby on Rails - Ecosystem
Be Happy With Ruby on Rails - Ecosystem
 
Simple Web Apps With Sinatra
Simple Web Apps With SinatraSimple Web Apps With Sinatra
Simple Web Apps With Sinatra
 
Introduction to HTML
Introduction to HTMLIntroduction to HTML
Introduction to HTML
 
spring3.2 java config Servler3
spring3.2 java config Servler3spring3.2 java config Servler3
spring3.2 java config Servler3
 
Optimizing AngularJS Application
Optimizing AngularJS ApplicationOptimizing AngularJS Application
Optimizing AngularJS Application
 
You're Doing It Wrong
You're Doing It WrongYou're Doing It Wrong
You're Doing It Wrong
 
You're Doing It Wrong
You're Doing It WrongYou're Doing It Wrong
You're Doing It Wrong
 

Mais de Richard Schneeman

Rails3 Summer of Code 2010 - Week 6
Rails3 Summer of Code 2010 - Week 6Rails3 Summer of Code 2010 - Week 6
Rails3 Summer of Code 2010 - Week 6
Richard Schneeman
 

Mais de Richard Schneeman (6)

Scaling the Web: Databases & NoSQL
Scaling the Web: Databases & NoSQLScaling the Web: Databases & NoSQL
Scaling the Web: Databases & NoSQL
 
Potential Friend Finder
Potential Friend FinderPotential Friend Finder
Potential Friend Finder
 
Rails3 Summer of Code 2010 - Week 6
Rails3 Summer of Code 2010 - Week 6Rails3 Summer of Code 2010 - Week 6
Rails3 Summer of Code 2010 - Week 6
 
Rails3 Summer of Code 2010- Week 5
Rails3 Summer of Code 2010- Week 5Rails3 Summer of Code 2010- Week 5
Rails3 Summer of Code 2010- Week 5
 
UT on Rails3 2010- Week 4
UT on Rails3 2010- Week 4 UT on Rails3 2010- Week 4
UT on Rails3 2010- Week 4
 
UT on Rails3 2010- Week 1
UT on Rails3 2010- Week 1UT on Rails3 2010- Week 1
UT on Rails3 2010- Week 1
 

Último

The basics of sentences session 4pptx.pptx
The basics of sentences session 4pptx.pptxThe basics of sentences session 4pptx.pptx
The basics of sentences session 4pptx.pptx
heathfieldcps1
 
SURVEY I created for uni project research
SURVEY I created for uni project researchSURVEY I created for uni project research
SURVEY I created for uni project research
CaitlinCummins3
 
Financial Accounting IFRS, 3rd Edition-dikompresi.pdf
Financial Accounting IFRS, 3rd Edition-dikompresi.pdfFinancial Accounting IFRS, 3rd Edition-dikompresi.pdf
Financial Accounting IFRS, 3rd Edition-dikompresi.pdf
MinawBelay
 
MSc Ag Genetics & Plant Breeding: Insights from Previous Year JNKVV Entrance ...
MSc Ag Genetics & Plant Breeding: Insights from Previous Year JNKVV Entrance ...MSc Ag Genetics & Plant Breeding: Insights from Previous Year JNKVV Entrance ...
MSc Ag Genetics & Plant Breeding: Insights from Previous Year JNKVV Entrance ...
Krashi Coaching
 

Último (20)

Spring gala 2024 photo slideshow - Celebrating School-Community Partnerships
Spring gala 2024 photo slideshow - Celebrating School-Community PartnershipsSpring gala 2024 photo slideshow - Celebrating School-Community Partnerships
Spring gala 2024 photo slideshow - Celebrating School-Community Partnerships
 
Championnat de France de Tennis de table/
Championnat de France de Tennis de table/Championnat de France de Tennis de table/
Championnat de France de Tennis de table/
 
ĐỀ THAM KHẢO KÌ THI TUYỂN SINH VÀO LỚP 10 MÔN TIẾNG ANH FORM 50 CÂU TRẮC NGHI...
ĐỀ THAM KHẢO KÌ THI TUYỂN SINH VÀO LỚP 10 MÔN TIẾNG ANH FORM 50 CÂU TRẮC NGHI...ĐỀ THAM KHẢO KÌ THI TUYỂN SINH VÀO LỚP 10 MÔN TIẾNG ANH FORM 50 CÂU TRẮC NGHI...
ĐỀ THAM KHẢO KÌ THI TUYỂN SINH VÀO LỚP 10 MÔN TIẾNG ANH FORM 50 CÂU TRẮC NGHI...
 
Incoming and Outgoing Shipments in 2 STEPS Using Odoo 17
Incoming and Outgoing Shipments in 2 STEPS Using Odoo 17Incoming and Outgoing Shipments in 2 STEPS Using Odoo 17
Incoming and Outgoing Shipments in 2 STEPS Using Odoo 17
 
The basics of sentences session 4pptx.pptx
The basics of sentences session 4pptx.pptxThe basics of sentences session 4pptx.pptx
The basics of sentences session 4pptx.pptx
 
UChicago CMSC 23320 - The Best Commit Messages of 2024
UChicago CMSC 23320 - The Best Commit Messages of 2024UChicago CMSC 23320 - The Best Commit Messages of 2024
UChicago CMSC 23320 - The Best Commit Messages of 2024
 
SURVEY I created for uni project research
SURVEY I created for uni project researchSURVEY I created for uni project research
SURVEY I created for uni project research
 
Software testing for project report .pdf
Software testing for project report .pdfSoftware testing for project report .pdf
Software testing for project report .pdf
 
An Overview of the Odoo 17 Discuss App.pptx
An Overview of the Odoo 17 Discuss App.pptxAn Overview of the Odoo 17 Discuss App.pptx
An Overview of the Odoo 17 Discuss App.pptx
 
philosophy and it's principles based on the life
philosophy and it's principles based on the lifephilosophy and it's principles based on the life
philosophy and it's principles based on the life
 
ANTI PARKISON DRUGS.pptx
ANTI         PARKISON          DRUGS.pptxANTI         PARKISON          DRUGS.pptx
ANTI PARKISON DRUGS.pptx
 
Operations Management - Book1.p - Dr. Abdulfatah A. Salem
Operations Management - Book1.p  - Dr. Abdulfatah A. SalemOperations Management - Book1.p  - Dr. Abdulfatah A. Salem
Operations Management - Book1.p - Dr. Abdulfatah A. Salem
 
Envelope of Discrepancy in Orthodontics: Enhancing Precision in Treatment
 Envelope of Discrepancy in Orthodontics: Enhancing Precision in Treatment Envelope of Discrepancy in Orthodontics: Enhancing Precision in Treatment
Envelope of Discrepancy in Orthodontics: Enhancing Precision in Treatment
 
Financial Accounting IFRS, 3rd Edition-dikompresi.pdf
Financial Accounting IFRS, 3rd Edition-dikompresi.pdfFinancial Accounting IFRS, 3rd Edition-dikompresi.pdf
Financial Accounting IFRS, 3rd Edition-dikompresi.pdf
 
Pragya Champions Chalice 2024 Prelims & Finals Q/A set, General Quiz
Pragya Champions Chalice 2024 Prelims & Finals Q/A set, General QuizPragya Champions Chalice 2024 Prelims & Finals Q/A set, General Quiz
Pragya Champions Chalice 2024 Prelims & Finals Q/A set, General Quiz
 
demyelinated disorder: multiple sclerosis.pptx
demyelinated disorder: multiple sclerosis.pptxdemyelinated disorder: multiple sclerosis.pptx
demyelinated disorder: multiple sclerosis.pptx
 
MSc Ag Genetics & Plant Breeding: Insights from Previous Year JNKVV Entrance ...
MSc Ag Genetics & Plant Breeding: Insights from Previous Year JNKVV Entrance ...MSc Ag Genetics & Plant Breeding: Insights from Previous Year JNKVV Entrance ...
MSc Ag Genetics & Plant Breeding: Insights from Previous Year JNKVV Entrance ...
 
....................Muslim-Law notes.pdf
....................Muslim-Law notes.pdf....................Muslim-Law notes.pdf
....................Muslim-Law notes.pdf
 
Stl Algorithms in C++ jjjjjjjjjjjjjjjjjj
Stl Algorithms in C++ jjjjjjjjjjjjjjjjjjStl Algorithms in C++ jjjjjjjjjjjjjjjjjj
Stl Algorithms in C++ jjjjjjjjjjjjjjjjjj
 
How to Manage Closest Location in Odoo 17 Inventory
How to Manage Closest Location in Odoo 17 InventoryHow to Manage Closest Location in Odoo 17 Inventory
How to Manage Closest Location in Odoo 17 Inventory
 

Rails 3 Beginner to Builder 2011 Week 8

  • 1. Beginner to Builder Week8 July, 2011 Monday, August 8, 11
  • 2. Rails - Week 8 • Dealing with nil • Acceptance Testing • Partials • Cells • Memcache @Schneems Monday, August 8, 11
  • 3. Dealing with Nil user = User.where(:username => "schneems").first #<User ... > user.image_url >> "/schneems.png" user = nil user.image_url # NameError: undefined local variable or method `user' for #<Object:0x1001dc288> @Schneems Monday, August 8, 11
  • 4. try to deal # use try from ActiveSupport user = User.where(:username => "schneems").first #<User ... > user.try(:image_url) || "/not_found.png" >> "/schneems.png" user = nil user.try(:image_url) || "/not_found.png" >> "/not_found.png" @Schneems Monday, August 8, 11
  • 5. || & ||= per_page = params[:per_page] per_page = 10 if per_page.blank? # instead per_page = params[:per_page]||10 # or per_page = params[:per_page] per_page ||= 10 @Schneems Monday, August 8, 11
  • 6. ‘if’ returns result # if returns to where it was called result = if true "foo" else "bar" end puts result >> "foo" result = if false "foo" else "bar" end puts result >> "bar" @Schneems Monday, August 8, 11
  • 7. Acceptance Testing • Run your full application stack • Behavior Driven Development (BDD) • High payout for little time testing • slow • potentially brittle @Schneems Monday, August 8, 11
  • 8. Capybara & Rspec • Capybara • Headless browser • open your webpages • click links ... Gemfile gem 'capybara', '0.3.7' gem 'rspec-rails', '1.3.2' @Schneems Monday, August 8, 11
  • 9. Capybara & Rspec # go to a path visit root_path visit "/" # click buttons click "sign in" # fill out forms fill_in ‘Email’, :with => "schneems@example.com" @Schneems Monday, August 8, 11
  • 10. Capybara & Rspec http://codingfrontier.com/integration-testing-setup-with-rspec-and-capy /spec/acceptance/signin_spec.rb context "as a guest on the sign in page" do # Generate a valid user let(:user) { Factory(:user) } context ‘with valid credentials’ do #Fill in the form with the user’s credentials and submit it. before do visit root_path click ‘Sign In’ fill_in ‘Email’, :with => user.email fill_in ‘Password’, :with => ‘password’ click ‘Submit’ end it "has a sign out link" do page.should have_xpath(‘//a’, :text => ‘Sign Out’) end it "knows who I am" do page.should have_content(“Welcome, #{user.email}!”) end end end @Schneems Monday, August 8, 11
  • 11. DRY Views • Helpers • Small resusable components • content_for • Control page flow of compnents out of normal placement • Partials • Large reusable components • Cells • type logic is needed when controller Reusable components @Schneems Monday, August 8, 11
  • 12. ViewHelpers • Rails has build in helpers • link_to • image_tag • etc. • Write your Own @Schneems Monday, August 8, 11
  • 13. ViewHelpers app/helpers/product_helper.rb link_to_product(product = nil) link_to image_tag(product.image_url), product_path(product), :class => 'product' end app/views/product/index.html.erb <%= link_to_product(@product) %> <a href=“...” class=”product”> <imgr src = “...” /> </a> @Schneems Monday, August 8, 11
  • 14. content_for & yield • Replace content using content_for <head> <title> <html> <%= yield :head %> <head> </title> <title>A simple page</title> </head> </head> <p>Hello, Rails!</p> <body> => <p>Hello, Rails!</p> <% content_for :head do %> </body> A simple page </html> <% end %> @Schneems Monday, August 8, 11
  • 15. content_for in layouts • use helpers & content_for together in layouts <body id="<%= id_for_body(yield(:body_id)) %>" class="<%= classes_for_body(yield(:body_class)) %> <%= logged_in? ? 'logged-in' : 'not-logged-in' %>"> <%= yield %> </body> @Schneems Monday, August 8, 11
  • 16. content_for in layouts # content_for head <%= yield :head_analytics %> <%= yield :head_stylesheets %> <%= yield :head_scripts %> <%= yield :head %> # content_for body <%= yield :main_title %> <%= yield :sidebar_title %> <%= yield :sidebar %> # content_for footer <%= yield :footer %> <%= yield :footer_libraries %> <%= yield :footer_scripts %> <%= yield :footer_analytics %> @Schneems Monday, August 8, 11
  • 17. Partials • Reusable chunks of view code <%# renders 'spots.html.erb' with @spot %> <%= render :partial => "spot", :object => @spot %> <%= render "spot", :object => @spot %> <%= render @spot %> <%# renders 'spots.html.erb' for each spot in @spots %> <%= render @spots %> <%= render "spot", :collection => @spots %> @Schneems Monday, August 8, 11
  • 18. Partials <%# renders 'spots.html.erb' for each spot in @spots %> <%= render @spots %> /spots/_spots.html.erb <div> <h3>Name:</h3> <p><%= spot.name %></p> <p><%= spot.description %></p> </div> @Schneems Monday, August 8, 11
  • 19. Partials • Locals <%# renders 'spots.html.erb' for each spot in @spots %> <%= render @spots, :locals => {:foo => ”bar”} %> /spots/_spots.html.erb <div> <h3>Name:</h3> <p><%= spot.name %></p> <p><%= spot.description %></p> <p><%= foo %></p> </div> @Schneems Monday, August 8, 11
  • 20. Partials • Optional Locals <%# renders 'spot.html.erb' for each spot in @spots %> <%= render @spot2 %> /spots/_spot.html.erb <div> <h3>Name:</h3> <p><%= spot.name %></p> <p><%= spot.description %></p> <p><%= local_assigns[:foo]||'something else' %></p> </div> @Schneems Monday, August 8, 11
  • 21. Cells • View Components • Look and Feel like Controllers gem install cells @Schneems Monday, August 8, 11
  • 22. Cells /app/views/product/index.html <div id="header"> <%= render_cell :cart, :display, :user => @current_user %> /app/cells/cart_cell.rb class CartCell < Cell::Rails def display(options) user = args[:user] @items = user.items_in_cart render # renders display.html.haml end end /app/cells/cart.display.html.erb <p>You have <%= @items.size %></p> @Schneems Monday, August 8, 11
  • 23. DRY Views • Helpers • Small resusable components • content_for • Control page flow of compnents out of normal placement • Partials • Large reusable components • Cells • type logic is needed when controller Reusable components @Schneems Monday, August 8, 11
  • 24. Caching • Store data in alater so it can be served quicker cache @Schneems Monday, August 8, 11
  • 25. Page Caching • Super Fast • Limited use cases class ProductsController < ActionController caches_page :index def index @products = Products.all end end http://guides.rubyonrails.org/caching_with_rails.html @Schneems Monday, August 8, 11
  • 26. Page Caching class ProductsController < ActionController caches_page :index def index @products = Products.all end def create expire_page :action => :index end end http://guides.rubyonrails.org/caching_with_rails.html @Schneems Monday, August 8, 11
  • 27. Action Caching • Allows Authentication checks class ProductsController < ActionController before_filter :authenticate caches_action :index def index @products = Product.all end def create expire_action :action => :index end end @Schneems Monday, August 8, 11
  • 28. Action Caching • :layout => false • allows dynamic currentthe layout to render such as info in user • :if & :unless • caches_action :index, :layout => false caches_action :index, :if => lambda {current_user.present?} caches_action :index, :unless => lambda {current_user.blank?} @Schneems Monday, August 8, 11
  • 29. Fragment Caching • Cache individual parts of pages <% cache('all_available_products') do %> All available products: <% end %> @Schneems Monday, August 8, 11
  • 30. Fragment Caching • Cache individual parts of pages <% cache(:action => 'recent', :action_suffix => 'all_products') do %> All available products: ... <%- end -%> @Schneems Monday, August 8, 11
  • 31. Fragment Caching • Expire fragments expire_fragment(:controller => 'products', :action => 'recent', :action_suffix => 'all_products') @Schneems Monday, August 8, 11
  • 32. Sweeping Cache class ProductsController < ActionController before_filter :authenticate caches_action :index cache_sweeper :product_sweeper def index @products = Product.all end end @Schneems Monday, August 8, 11
  • 33. Sweeping Cache class ProductSweeper < ActionController::Caching::Sweeper observe Product # This sweeper is going to keep an eye on the Product model # If our sweeper detects that a Product was created call this def after_create(product) expire_cache_for(product) end private def expire_cache_for(product) # Expire the index page now that we added a new product expire_page(:controller => 'products', :action => 'index') expire_fragment('all_available_products') end end @Schneems Monday, August 8, 11
  • 34. Cache Stores • Set the Cache store in your environment ActionController::Base.cache_store = :memory_store ActionController::Base.cache_store = :drb_store, "druby://localhost:9192" ActionController::Base.cache_store = :mem_cache_store, "localhost" @Schneems Monday, August 8, 11
  • 35. Cache Stores • Simple Key/Value storage Rails.cache.read("city") # => nil Rails.cache.write("city", "Duckburgh") Rails.cache.read("city") # => "Duckburgh" @Schneems Monday, August 8, 11
  • 36. Cache Stores • fetch Rails.cache.read("city") # => nil Rails.cache.fetch("city") do "Duckburgh" end # => "Duckburgh" Rails.cache.read("city") # => "Duckburgh" @Schneems Monday, August 8, 11
  • 37. Cache Stores • Expires_in Rails.cache.write("city", "Duckburgh", :expires_in => 1.minute) Rails.cache.read("city") # => "Duckburgh" sleep 120 Rails.cache.read("city") # => nil @Schneems Monday, August 8, 11
  • 38. Memcache • Cache your rails objects • Memcache Gem • Key Value Store (NOSQL) • Use to cache Expensive Queries require 'memcached' $cache = Memcached.new("localhost:11211") $cache.set("foo", "bar") $cache.get("foo") => "bar" @Schneems Monday, August 8, 11
  • 39. Memcache # store strings $cache.set("key", "value") $cache.get("key") => "bar" # store any ruby object $cache.set("foo", [1,2,3,4,5]) $cache.get("foo") => [1,2,3,4,5] # srsly any ruby object $cache.set("foo", User.last) $cache.get("foo") => #< User ... > @Schneems Monday, August 8, 11
  • 40. Memcache ActionController::Base.cache_store = :mem_cache_store, "localhost" @Schneems Monday, August 8, 11
  • 41. Memcache • Cache frequent queries class User < ActiveRecord::Base def self.fetch(username) Rails.cache.fetch("user:#{username}") do User.where(:username => "#{username}").first end end end => User.fetch("schneems") #=> #<User id: 263595 ... > @Schneems Monday, August 8, 11
  • 42. Memcache • Cache expensive queries class User < ActiveRecord::Base def fetch_friends Rails.cache.fetch("users:friends:#{self.id}") do friends = Friendships.where(:user_1_id => self.id) end end end => User.fetch("schneems").fetch_friend_ids @Schneems Monday, August 8, 11
  • 43. Memcache • Blazing Fast # Database Benchmark.measure do User.where(:username => "schneems").first end.real => 0.09 s # Memcache Benchmark.measure do User.fetch("schneems") end.real => 0.0009 s @Schneems Monday, August 8, 11
  • 44. Memcache • Key Value Store • Holds ruby objects • Extremely fast • volatile • available on Heroku >> heroku addons:add memcache @Schneems Monday, August 8, 11
  • 45. Bonus - Keytar class User < ActiveRecord::Base • includeKeytar to generate Keys Use Keytar define_keys :username, :friends • end Use those keys in Memcache User.username_key("schneems") => "user:username:schneems" user = Rails.cache.fetch(User.username_key("schneems")) => # < User id:33 ... > user.friends_key => "users:friends:33" friends = Rails.cache.fetch(user.friends_key) => #[#< User ... >, #< User ... >, ... ] @Schneems Monday, August 8, 11
  • 46. Questions? http://guides.rubyonrails.org http://stackoverflow.com http://peepcode.com @Schneems Monday, August 8, 11