Ce diaporama a bien été signalé.
Nous utilisons votre profil LinkedIn et vos données d’activité pour vous proposer des publicités personnalisées et pertinentes. Vous pouvez changer vos préférences de publicités à tout moment.
Rails Best Practices
              ihower@gmail.com




  As this slide writing, the current Rails version is 2.3.4
Who am I ?
•           a.k.a. ihower
    • http://ihower.tw
    • http://twitter.com/ihower
    • http://github.com/ihower...
Ruby Taiwan
  http://ruby.tw
Agenda
• Concept: What’s good code?
• Move Code from Controller to Model
• RESTful best practices
• Model best practices
•...
Warning! you should have testing before modify!
Best Practice Lesson 0:

Concepts
Why best practices?


• Large & complicated application
• Team & different coding style
Your code become...
•   (Rigidity)

•   (Fragility)
•   (Immobility)
•   (Viscosity)
•                   (Needless Complex...
We need good code:
What’s Good code?
• Readability
• Flexibility
• Effective
• Maintainability
• Consistency
• Testability
So, What we can do?
Best Practice Lesson 1:

Move code from Controller to
           Model
        action code                       15
     h...
Before


        1.Move finder to named_scope
class PostsController < ApplicationController

  def index
    @public_posts ...
After


      1.Move finder to named_scope
class UsersController < ApplicationController

  def index
    @published_post =...
Before


2. Use model association

class PostsController < ApplicationController

  def create
    @post = Post.new(params...
After


      2. Use model association
class PostsController < ApplicationController

  def create
    @post = current_use...
3. Use scope access
                                                Before




class PostsController < ApplicationControll...
3. Use scope access
                                                            After




class PostsController < Applicat...
Before


      4. Add model virtual attribute
<% form_for @user do |f| %>
    <%= text_filed_tag :full_name %>
<% end %>

...
After


4. Add model virtual attribute
    class User < ActiveRecord::Base

      def full_name
        [first_name, last_...
After




<% form_for @user do |f| %>
  <%= f.text_field :full_name %>
<% end %>

class UsersController < ApplicationContr...
5. Use model callback                                Before




<% form_for @post do |f| %>
  <%= f.text_field :content %>...
After


 5. Use model callback
class Post < ActiveRecord::Base

  attr_accessor :auto_tagging
  before_save :generate_tagg...
After




<% form_for :note, ... do |f| %>
  <%= f.text_field :content %>
  <%= f.check_box :auto_tagging %>
<% end

class...
6. Replace Complex Creation                             Before




    with Factory Method
  class InvoiceController < App...
6. Replace Complex Creation
                                                     After




    with Factory Method
  class...
After




class InvoiceController < ApplicationController
  def create
    @invoice = Invoice.new_by_user(params[:invoice]...
7. Move Model Logic into the                       Before




          Model
 class PostController < ApplicationControlle...
7. Move Model Logic into the                 After




          Model
   class Post < ActiveRecord::Base

     def publis...
After




class PostController < ApplicationController

  def publish
    @post = Post.find(params[:id])
    @post.publish...
8. model.collection_model_ids
            (many-to-many)
class User < ActiveRecord::Base

  has_many :user_role_relationsh...
Before


<% form_for @user do |f| %>
  <%= f.text_field :email %>
  <% for role in Role.all %>
    <%= check_box_tag 'role...
After

<% form_for @user do |f| %>

 <% for role in Role.all %>
  <%= check_box_tag 'user[role_ids][]', role.id, @user.rol...
9. Nested Model Forms (one-to-one)               Before




    class Product < ActiveRecord::Base
      has_one :detail
 ...
Before




class Product < ApplicationController

  def create
    @product = Product.new(params[:product])
    @details =...
9. Nested Model Forms (one-to-one)                After


              Rails 2.3 new feature

     class Product < Active...
After




class Product < ApplicationController

  def create
    @product = Product.new(params[:product])
    @product.sa...
10. Nested Model Forms (one-to-many)
      class Project < ActiveRecord::Base
        has_many :tasks
        accepts_nest...
Nested Model Forms
              before Rails 2.3 ?

•   Ryan Bates’s series of railscasts on complex forms
    •   http:/...
Best Practice Lesson 2:


RESTful
  RESTful conventions
Why RESTful?
RESTful help you to organize/name controllers, routes
         and actions in standardization way
Before


class EventsController < ApplicationController



  def index                                def white_member_lis...
After



class EventsController < ApplicationController
  def index; end
  def show; end
end

class   CommentsControlers <...
Before



1. Overuse route customizations

map.resources :posts, :member => { :comments   => :get,
                       ...
After



1. Overuse route customizations
         Find another resources


       map.resources :posts do |post|
         ...
Suppose we has a event model...

   class Event < ActiveRecord::Base

     has_many :attendee
     has_one :map

     has_...
Can you answer how to design
      your resources ?
•   manage event attendees (one-to-many)
•   manage event map (one-to-...
Learn RESTful design
                 my slide about restful:
http://www.slideshare.net/ihower/practical-rails2-350619
Before

            2. Needless deep nesting
                            : Never more than one level




        map.resou...
After

 2. Needless deep nesting
                 : Never more than one level




  map.resources :posts do |post|
    pos...
Before


  3. Not use default route

map.resources :posts, :member => { :push => :post }

map.connect ':controller/:action...
After


        3. Not use default route

map.resources :posts, :member => { :push => :post }

#map.connect ':controller/:...
Best Practice Lesson 3:

   Model
Before

1. Keep Finders on Their Own Model
 class Post < ActiveRecord::Base
   has_many :comments

   def find_valid_comme...
After

1. Keep Finders on Their Own Model
  class Post < ActiveRecord::Base
    has_many :comments
  end

  class Comment ...
Before

                  2. Love named_scope
class PostController < ApplicationController

  def search
    conditions = ...
After

        2. Love named_scope
class Post < ActiveRecord::Base

  named_scope :matching, lambda { |column, value|
    ...
After




class PostController < ApplicationController

  def search
    @posts = Post.matching(:title, params[:title])
  ...
Before



3. the Law of Demeter
 class Invoice < ActiveRecord::Base
   belongs_to :user
 end

 <%= @invoice.user.name %>
 ...
After



     3. the Law of Demeter
class Invoice < ActiveRecord::Base
  belongs_to :user
  delegate :name, :address, :cel...
4. DRY: Metaprogramming
                                                                         Before



class Post < Ac...
4. DRY: Metaprogramming
                                                               After




class Post < ActiveRecord...
Breaking Up Models
      Model
Before



5. Extract into Module
 class User < ActiveRecord::Base

   validates_presence_of :cellphone
   before_save :par...
After
# /lib/has_cellphone.rb
module HasCellphone

  def self.included(base)
    base.validates_presence_of :cellphone
   ...
After




class User < ActiveRecord::Base

  include HasCellphone

end
Before

6. Extract to composed class
# == Schema Information
# address_city          :string(255)
# address_street        ...
6. Extract to composed class                                                   After



                        (value obj...
Before


             7. Use Observer
class Project < ActiveRecord::Base

  after_create :send_create_notifications

  pri...
After


             7. Use Observer
class Project < ActiveRecord::Base
  # nothing here
end

# app/observers/project_noti...
Best Practice Lesson 4:

Migration
Before


            1. Isolating Seed Data
class CreateRoles < ActiveRecord::Migration
  def self.up
    create_table "ro...
After


         1. Isolating Seed Data

# /db/seeds.rb (Rails 2.3.4)
["admin", "author", "editor","account"].each do |nam...
After




# /lib/tasks/dev.rake (before Rails 2.3.4)

namespace :dev do

  desc "Setup seed data"
  task :setup => :enviro...
Before


   2. Always add DB index
class CreateComments < ActiveRecord::Migration
  def self.up
    create_table "comments...
After


   2. Always add DB index
class CreateComments < ActiveRecord::Migration
  def self.up
    create_table "comments"...
Best Practice Lesson 5:

Controller
1. Use before_filter                         Before




class PostController < ApplicationController

  def show
    @post ...
1. Use before_filter                                 After




class PostController < ApplicationController

  before_filte...
Before


                   2. DRY Controller
class PostController < ApplicationController

  def index                   ...
After


       2. DRY Controller
http://github.com/josevalim/inherited_resources

class PostController < InheritedResource...
After


        2. DRY Controller
class PostController < InheritedResources::Base

  # if you need customize redirect url
...
DRY Controller Debate!!

 • You lose intent and readability
 • Deviating from standards makes it harder
    to work with o...
Best Practice Lesson 6:

    View
Never logic code in Views
1. Move code into controller
Before   <% @posts = Post.find(:all) %>
         <% @posts.each do |post| %>
          <%=h p...
2. Move code into model
Before   <% if current_user && (current_user == @post.user ||
                                @pos...
Before     3. Move code into helper
<%= select_tag :state, options_for_select( [[t(:draft),"draft" ],
                    ...
4. Replace instance variable
               with local variable
         class Post < ApplicationController
           def...
Before

        5. Use Form Builder
<% form_for @post do |f| %>

  <p>
     <%= f.label :title, t("post.title") %> <br>
  ...
After

            5. Use Form Builder

<% my_form_for @post do |f| %>

  <%= f.text_field :title, :label => t("post.title...
After
module ApplicationHelper
  def my_form_for(*args, &block)
    options = args.extract_options!.merge(:builder =>
Labe...
6. Organize Helper files
         #   app/helpers/user_posts_helper.rb
Before   #   app/helpers/author_posts_helper.rb
    ...
7. Learn Rails Helpers

• Learn content_for and yield
• Learn how to pass block parameter in helper
 •   my slide about he...
Best Practice Lesson 7:

Code Refactoring
We have Ruby edition now!!
      Must read it!
Reference:
         :
http://weblog.jamisbuck.org/2006/10/18/skinny-controller-fat-model
http://www.matthewpaulmoore.com/r...
Thank you.
After 2. DRY Controller http://github.com/josevalim/inherited_resources
Prochain SlideShare
Chargement dans…5
×

After 2. DRY Controller http://github.com/josevalim/inherited_resources Rails Best Practices

145 636 vues

Publié le

After


2. DRY Controller
http://github.com/josevalim/inherited_resources

class PostController < InheritedResources::Base

# magic!! nothing here!

end

Publié dans : Industrie automobile
  • Dating direct: ♥♥♥ http://bit.ly/369VOVb ♥♥♥
       Répondre 
    Voulez-vous vraiment ?  Oui  Non
    Votre message apparaîtra ici
  • Dating for everyone is here: ❶❶❶ http://bit.ly/369VOVb ❶❶❶
       Répondre 
    Voulez-vous vraiment ?  Oui  Non
    Votre message apparaîtra ici
  • DOWNLOAD THIS BOOKS INTO AVAILABLE FORMAT (2019 Update) ......................................................................................................................... ......................................................................................................................... Download Full PDF EBOOK here { https://tinyurl.com/ubg3cxe } ......................................................................................................................... Download Full EPUB Ebook here { https://tinyurl.com/ubg3cxe } ......................................................................................................................... Download Full doc Ebook here { https://tinyurl.com/ubg3cxe } ......................................................................................................................... Download PDF EBOOK here { https://tinyurl.com/ubg3cxe } ......................................................................................................................... Download EPUB Ebook here { https://tinyurl.com/ubg3cxe } ......................................................................................................................... Download doc Ebook here { https://tinyurl.com/ubg3cxe } ......................................................................................................................... .........................................................................................................................
       Répondre 
    Voulez-vous vraiment ?  Oui  Non
    Votre message apparaîtra ici
  • DOWNLOAD THIS BOOKS INTO AVAILABLE FORMAT (2019 Update) ......................................................................................................................... ......................................................................................................................... Download Full PDF EBOOK here { https://soo.gd/irt2 } ......................................................................................................................... Download Full EPUB Ebook here { https://soo.gd/irt2 } ......................................................................................................................... Download Full doc Ebook here { https://soo.gd/irt2 } ......................................................................................................................... Download PDF EBOOK here { https://soo.gd/irt2 } ......................................................................................................................... Download EPUB Ebook here { https://soo.gd/irt2 } ......................................................................................................................... Download doc Ebook here { https://soo.gd/irt2 } ......................................................................................................................... ......................................................................................................................... ................................................................................................................................... eBook is an electronic version of a traditional print book THIS can be read by using a personal computer or by using an eBook reader. (An eBook reader can be a software application for use on a computer such as Microsoft's free Reader application, or a book-sized computer THIS is used solely as a reading device such as Nuvomedia's Rocket eBook.) Users can purchase an eBook on diskette or CD, but the most popular method of getting an eBook is to purchase a downloadable file of the eBook (or other reading material) from a Web site (such as Barnes and Noble) to be read from the user's computer or reading device. Generally, an eBook can be downloaded in five minutes or less ......................................................................................................................... .............. Browse by Genre Available eBooks .............................................................................................................................. Art, Biography, Business, Chick Lit, Children's, Christian, Classics, Comics, Contemporary, Cookbooks, Manga, Memoir, Music, Mystery, Non Fiction, Paranormal, Philosophy, Poetry, Psychology, Religion, Romance, Science, Science Fiction, Self Help, Suspense, Spirituality, Sports, Thriller, Travel, Young Adult, Crime, Ebooks, Fantasy, Fiction, Graphic Novels, Historical Fiction, History, Horror, Humor And Comedy, ......................................................................................................................... ......................................................................................................................... .....BEST SELLER FOR EBOOK RECOMMEND............................................................. ......................................................................................................................... Blowout: Corrupted Democracy, Rogue State Russia, and the Richest, Most Destructive Industry on Earth,-- The Ride of a Lifetime: Lessons Learned from 15 Years as CEO of the Walt Disney Company,-- Call Sign Chaos: Learning to Lead,-- StrengthsFinder 2.0,-- Stillness Is the Key,-- She Said: Breaking the Sexual Harassment Story THIS Helped Ignite a Movement,-- Atomic Habits: An Easy &amp; Proven Way to Build Good Habits &amp; Break Bad Ones,-- Everything Is Figureoutable,-- What It Takes: Lessons in the Pursuit of Excellence,-- Rich Dad Poor Dad: What the Rich Teach Their Kids About Money THIS the Poor and Middle Class Do Not!,-- The Total Money Makeover: Classic Edition: A Proven Plan for Financial Fitness,-- Shut Up and Listen!: Hard Business Truths THIS Will Help You Succeed, ......................................................................................................................... .........................................................................................................................
       Répondre 
    Voulez-vous vraiment ?  Oui  Non
    Votre message apparaîtra ici
  • DOWNLOAD THIS BOOKS INTO AVAILABLE FORMAT (2019 Update) ......................................................................................................................... ......................................................................................................................... Download Full PDF EBOOK here { https://soo.gd/irt2 } ......................................................................................................................... Download Full EPUB Ebook here { https://soo.gd/irt2 } ......................................................................................................................... Download Full doc Ebook here { https://soo.gd/irt2 } ......................................................................................................................... Download PDF EBOOK here { https://soo.gd/irt2 } ......................................................................................................................... Download EPUB Ebook here { https://soo.gd/irt2 } ......................................................................................................................... Download doc Ebook here { https://soo.gd/irt2 } ......................................................................................................................... ......................................................................................................................... ................................................................................................................................... eBook is an electronic version of a traditional print book THIS can be read by using a personal computer or by using an eBook reader. (An eBook reader can be a software application for use on a computer such as Microsoft's free Reader application, or a book-sized computer THIS is used solely as a reading device such as Nuvomedia's Rocket eBook.) Users can purchase an eBook on diskette or CD, but the most popular method of getting an eBook is to purchase a downloadable file of the eBook (or other reading material) from a Web site (such as Barnes and Noble) to be read from the user's computer or reading device. Generally, an eBook can be downloaded in five minutes or less ......................................................................................................................... .............. Browse by Genre Available eBooks .............................................................................................................................. Art, Biography, Business, Chick Lit, Children's, Christian, Classics, Comics, Contemporary, Cookbooks, Manga, Memoir, Music, Mystery, Non Fiction, Paranormal, Philosophy, Poetry, Psychology, Religion, Romance, Science, Science Fiction, Self Help, Suspense, Spirituality, Sports, Thriller, Travel, Young Adult, Crime, Ebooks, Fantasy, Fiction, Graphic Novels, Historical Fiction, History, Horror, Humor And Comedy, ......................................................................................................................... ......................................................................................................................... .....BEST SELLER FOR EBOOK RECOMMEND............................................................. ......................................................................................................................... Blowout: Corrupted Democracy, Rogue State Russia, and the Richest, Most Destructive Industry on Earth,-- The Ride of a Lifetime: Lessons Learned from 15 Years as CEO of the Walt Disney Company,-- Call Sign Chaos: Learning to Lead,-- StrengthsFinder 2.0,-- Stillness Is the Key,-- She Said: Breaking the Sexual Harassment Story THIS Helped Ignite a Movement,-- Atomic Habits: An Easy &amp; Proven Way to Build Good Habits &amp; Break Bad Ones,-- Everything Is Figureoutable,-- What It Takes: Lessons in the Pursuit of Excellence,-- Rich Dad Poor Dad: What the Rich Teach Their Kids About Money THIS the Poor and Middle Class Do Not!,-- The Total Money Makeover: Classic Edition: A Proven Plan for Financial Fitness,-- Shut Up and Listen!: Hard Business Truths THIS Will Help You Succeed, ......................................................................................................................... .........................................................................................................................
       Répondre 
    Voulez-vous vraiment ?  Oui  Non
    Votre message apparaîtra ici

×