Skip to content

Instantly share code, notes, and snippets.

@deeeki
Created November 18, 2011 12:16
Show Gist options
  • Save deeeki/1376304 to your computer and use it in GitHub Desktop.
Save deeeki/1376304 to your computer and use it in GitHub Desktop.
細かすぎて伝わらないRails

※主観的かつ個人的な試行錯誤の備忘録です

Coding Style

クラスマクロの順序

  • Model
  • associations
  • attr_accessors
  • scopes
  • validations
  • callbacks
  • Controller
  • layout
  • callbacks

##メソッドの順序

  • Model
  • singleton methods (class methods)
  • business logic methods
  • predicate methods (returned boolean value)
  • formatted methods (mainly used in views)
  • protected and private methods
  • Controller
  • index, show, new, create, edit, update, destroy (order in scaffold)
  • other actions
  • private methods

##その他

  • シングルクォート優先

Tips

##コールバックで対象インスタンスロード before_filter :prefetch_instance, :except => [:index] private def prefetch_instance @instance = Model.find params[:id] rescue redirect_to :action => :index, :alert => 'not found' end

Issues

##マスタデータ

  • モデル定義
  • アソシエーションつけやすいけど煩雑
  • 定数定義
  • 完全固定なものは lib/master.rb 作ってクラス定数でハッシュ定義してる
  • Ruby1.9だと順序保証なので扱いやすい
  • keyが表示用名称でvalueがコード

##リソース分割 VS アクション追加

  • 例えばユーザーのパスワード変更
  • resources :user {resource :password, :only => [:edit, :update]} などとすべきか
  • edit_password/update_password のアクション追加で済ますか

##表示用フォーマット Model VS Helper

  • Modelで定義したほうがいいと思ってる
  • htmlタグを含むような場合はHelper
  • 抽象化したフォーマット用メソッドはlibにおいてる

##関連モデルの命名

  • 例えばUserのProfileをわけたとしてUserProfileにはしなくていいと思う
  • 極力シンプルに、安易に連結せずに適切な単語を探す

##url_forの引数

  • シンプルな順に優先したい
  • モデル直接指定 (namespace付きの場合は[:namespace, @model])
  • シンボル
  • ヘルパーメソッド
  • 直接指定はroutingがネストしてるとうまくいかないこともある気がする

##クラスの中でのメソッド呼び出し

  • 基本self.はつけなくていいものだろうか

##フィールドのデフォルト値

  • DBのスキーマで定義
  • before_createで定義 before_create self.field ||= default_value end
  • booleanのとき注意しないといけない
  • デフォルトtrueは上のコードではだめで型までみる必要がある
  • デフォルトfalseは最後に記述すると返り値と認識されてsaveが動作しない
  • https://github.com/bbatsov/rails-style-guide#migrations
  • ここにあるメソッド定義はやり過ぎだと思う

##カラムの値のコードの扱い

  • 0から
  • 1から
  • 例外的に-1を使うのはありか

##選択式項目で「その他」という自由入力がある

  • めんどい(´・ω・`)
  • integer の field と string の field_other でがんばる
  • string の field のみにして入力のUIを工夫する

##Serviceクラスの必要性

  • Modelでなんとかなる気がしてる
  • 作るとしても粒度や命名が悩ましいかも

##Nested Attributes

  • 確認画面と組み合わせると地獄、というか無理
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment