0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

【Rails】sendを使ってメタプロっぽい書き方をしたので記しておく

Posted at

タイトル通り、sendメソッドを使ってメタプロっぽい書き方をやってみたので書き残しておく。

説明

deviseで clientcreatorという2つのモデルを用意している。
それぞれ、nameが登録されているか/されていないかによって、ログイン後の繊維ページが異なるが、
clientとcreator間での法則性は同一である。
↓こんな感じ

name登録済み name未登録
client client_mypage_path edit_client_path(current_client)
creator creator_mypage_path edit_creator_path(current_creator)

send使ってafter_sign_in_path_for

application_controller.rb
class ApplicationController < ActionController::Base
  helper_method :current_resource, :current_resource_model, :other_side_model, :registered_name?

  def current_resource
    if client_signed_in?
      current_client
    elsif creator_signed_in?
      current_creator
    end
  end

  def current_resource_model
    return unless current_resource
    current_resource.class.to_s.downcase
  end

  # ログイン後に遷移するpathを設定
  def after_sign_in_path_for(resource)
    return unless current_resource
    resource_mypage_path = send(current_resource_model + "_mypage_path")
    edit_resource_path = send("edit_" + current_resource_model + "_path", current_resource)
    
    registered_name? ? resource_mypage_path : edit_resource_path
  end

  def registered_name?
    current_resource&.name.present?
  end

このように、複数のdeviseモデルでの法則的なコードを1つにまとめて記述する時に役に立ちそう。

0
0
2

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
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?