Skip to content

Instantly share code, notes, and snippets.

@marocchino
Created June 22, 2012 01:20
Show Gist options
  • Save marocchino/2969674 to your computer and use it in GitHub Desktop.
Save marocchino/2969674 to your computer and use it in GitHub Desktop.
코딩컨밴션 2012/07 추가분

1. 行末の空白の削除

http://rails-bestpractices.com/posts/60-remove-trailing-whitespace

"Trailing whitespace always makes noises in version control system, it is meaningless. We should remove trailing whitespace to avoid annoying other team members." 行末の空白はいつもヴァージョン管理システムで意味の無い雑音を作る。他の仲間の為に行末の空白の削除するべきだ。

でvimrcに下の奴を追加してください。

" Strip trailing whitespace
function! <SID>StripTrailingWhitespaces()
    " Preparation: save last search, and cursor position.
    let _s=@/
    let l = line(".")
    let c = col(".")
    " Do the business:
    %s/\s\+$//e
    " Clean up: restore previous search history, and cursor position
    let @/=_s
    call cursor(l, c)
endfunction
autocmd BufWritePre * :call <SID>StripTrailingWhitespaces()

2. パラメータ変造攻撃に備える

http://rails-bestpractices.com/posts/148-protect-mass-assignment

例えはUserの中にadminと言うコラムがある時

class User < ActiveRecord::Base
end

class UsersController < ApplicationController
  def update
    # X : params[:user][:admin] = true にするとかの攻撃が出来る。
    if current_user.update_attributes(params[:user]) 
      # do something
    end
  end
end

attr_accessibleをモデルに書くことにすると問題無し。

class User < ActiveRecord::Base
  attr_accessible :email, :password, :password_confirmation, :remember_me
  # O : ここに登録されて無いものを修正しようとするとエーラに成る
end

refactor

class Invoice < ActiveRecord::Base
  belongs_to :user
  delegate :name, :address, :cellphone, :to => :user, :prefix => true
end
<%= @invoice.user_name %>
<%= @invoice.user_address %>
<%= @invoice.user_cellphone %>

4. 3-6 に追加

# X
map.resources :download, :member => {:some => :get}, :collection => { :spec => :get }
# O
map.resources :downloads, :member => {:some => :get}, :collection => { :spec => :get }

# X
map.resource :browsers, :controller => :browser, :collection => { :check => :get }
# O
map.resource :browser, :controller => :browser, :collection => { :check => :get }

# X
map.resource :browser, :controller => :browser, :collection => { :index => :get }, :only => [:show]
# O
map.resources :browsers, :only => [:index, :show]

5. 10-1の変更

必ずSanitizeが出来るようにする。 他の開発者から見るとごれが内部か外部かを判断するのが難しい為、内部変数て攻撃の可能性がない場合にもこのルールは適用されるべきです。

BAD EXAMPLE
  named_scope :by_id, lambda { |id|
      { :conditions => ["id = #{id}"] }
  }
GOOD EXAMPLE
  named_scope :by_id, lambda { |id|
      { :conditions => ["id = ?",id] }
  }
  # or 
  named_scope :by_id, lambda { |id|
      { :conditions => {:id => id } }
  }

6. 11の変更

1.デバッグメッセージなどはなるべくRailsのLOGGERを使う。PUTSは遠慮してもらう。

puts "#############################log for debug = #{somedata}" # x
logger.debug { "#############################log for debug = #{somedata}" } # o

2.BLOCKを使わないと デバッグしない時も解析されてしまうので必ずBLOCKにしてください。

logger.debug "#############################log for debug = #{User.first}" # x
logger.debug { "#############################log for debug = #{User.first}" } # o

7. 14の削除

メッセージを定義すべき場所は、メッセージの意味上のレイヤで決めるべきです。modelを除外する理由が浅いため、不要なルールとします。 例:ユーザーオブジェクトについて言っているメッセージ → Userモデルに定義 例:ユーザー登録画面上のメッセージ → RegisterHelperヘルパーに定義

8. 17の変更

DRYコードが2回以上繰り返すな。 コードはなるべくmodule化して中復して書かないようにしましょう。 http://ja.wikipedia.org/wiki/Don't_repeat_yourself

10. cache object はNULLの対策をいつもする事

下の例だとinviterが無い時gameを読んでもserviceを読んでもエーラになる。 cache objectはいつ読んでもエーラにならない風に実装してください。

  def inviter
    @inviter ||= Inviter.find_by_id(params[:id])
  end

  def game
    @game ||= Game.find_by_ssn(inviter.ssn)
  end

  def service
    @service ||= game.game_name
  end
  def inviter
    @inviter ||= Inviter.find_by_id(params[:id])
  end

  def game
    @game ||= inviter && Game.find_by_ssn(inviter.ssn)
  end

  def service
    @service ||= game.try(:game_name) || "pmang"
  end

11. 異常系のURLに対応しましょう。

通常おこらないURLでのリクエストに対して、500:Internal Server Errorが出てしまうことがないようにしましょう。 多くのケースでは404:Not Foundを返すと適切でしょう。

  # X
  def show
    @inviter = Inviter.find_by_id(params[:id])
    # @inviter == nil の場合に、Internal Server Error 
    @game    = Game.find_by_ssn(inviter.ssn) 
  end

  # O
  def show
    if @inviter = Inviter.find_by_id(params[:id])
      @game    = Game.find_by_ssn(inviter.ssn) 
    else 
      head :not_found
    end
  end

参考

ここからはcoding conventionには入らないが一様読んでほしいものです。

3. デメテルの法則

http://ja.wikipedia.org/wiki/%E3%83%87%E3%83%A1%E3%83%86%E3%83%AB%E3%81%AE%E6%B3%95%E5%89%87 http://rails-bestpractices.com/posts/15-the-law-of-demeter

bed small

class Invoice < ActiveRecord::Base
  belongs_to :user
end
<%= @invoice.user.name %>
<%= @invoice.user.address %>
<%= @invoice.user.cellphone %>

9. 今直ぐ必要で無いものは削除

http://ja.wikipedia.org/wiki/YAGNI

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment