LoginSignup
6
4

More than 5 years have passed since last update.

Rails controller で早期で綺麗にreturnする方法

Last updated at Posted at 2016-11-04

コントローラーを使い込んできたときに使える。早期で綺麗にreturnする方法です。
メイン処理に影響を与えないパターンでGuard Clauseとか呼ばれている。

まず通常

早期リターンを使いこなすだけでも、本筋の処理が見えてわかりやすい。
このままでもいいけどね。

def add_friend

if @friend.has_no_money?
  redirect_to "/"
  return
end

@friend.welcome

end

テクニック1

後置ifと and で繋げる。無理な要求してたときに乱暴に返したいときに使える。

def add_friend
redirect_to "/" and return if @friend.has_no_money?

@friend.welcome
end

テクニック2

丁寧に返すとメッセージ文だけで増えてくるので、
早期リターンをメソッドに分けるのだ。
これがお気に入り。(trueを返すのが気になるけど)

def add_friend
skip_no_money and return

@friend.welcome
end

private
def skip_no_money
  if @friend.no_money?
    redirect_to "/", notice: 'Sorry, You are not acceptable.'
    return true 
  end
end

テクニック3

あとは、アクション前に拾ってしまう。

before_action :skip_no_money, only: [:add_friend]

参考
http://qiita.com/wadako111/items/54c3dcf6c5fc03b04678
http://blog.arkency.com/2014/07/4-ways-to-early-return-from-a-rails-controller/

6
4
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
6
4