LoginSignup
6
6

Ruby - 呼び出されているmethod名を検知してrefactoring

Last updated at Posted at 2015-07-30

#やりたいこと

  • 呼ばれているメソッド名を検知して、それをメソッド内部のリファクタリングに利用したい。

#メソッド名検知

  • __method__: メソッド名をシンボルとして返す。
  • __callee__: エイリアスメソッド名をシンボルとして返す。

#Refactoring例

Before

class OmniauthCallbacksController < Devise::OmniauthCallbacksController

  def facebook
    user = User.from_omniauth(request.env["omniauth.auth"])
    if user.persisted?
      set_flash_message(:notice, :success, kind: "Facebook") if is_navigational_format?
      sign_in_and_redirect user, event: :authentication
    else
      session["devise.user_attributes"] = user.attributes
      redirect_to new_user_registration_url
    end
  end

  def twitter
    user = User.from_omniauth(request.env["omniauth.auth"])
    if user.persisted?
      set_flash_message(:notice, :success, kind: "Twitter") if is_navigational_format?
      sign_in_and_redirect user, event: :authentication
    else
      session["devise.user_attributes"] = user.attributes
      redirect_to new_user_registration_url
    end
  end
end

After


class OmniauthCallbacksController < Devise::OmniauthCallbacksController

  def callback_for_all_providers
    provider = __callee__.to_s  # エイリアスメソッド名を読みこみ、文字列として利用。

    user = User.from_omniauth(request.env["omniauth.auth"])
    if user.persisted?
      sign_in_and_redirect user, event: :authentication
      set_flash_message(:notice, :success, kind: provider.capitalize) if is_navigational_format?
    else
      session["devise.user_attributes"] = user.attributes
      redirect_to new_user_registration_url
    end
  end

  alias_method :twitter, :callback_for_all_providers
  alias_method :facebook, :callback_for_all_providers
end
6
6
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
6