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?

Railsのイディオム的なもの

Posted at

始まりは挨拶から

はじめまして、最近リファクタリングに興味を持っているあおげばにゃんこです。
Ruby on Railsを書いている時に便利だなと思った書き方を簡単に紹介したいと思います

インスタンスの初期化時にデータをセットする

やりたいこと => 自分のおもちゃを箱にしまうフォームを作成

最初に思いつく処理

直入れすれば良いっしょ!

class BoxesController < ApplicationController
  def new
    @box = ToyBox.new(
      toy_car: current_user.toys[:toy_car],
      doll: current_user.toys[:doll],
      puzzle: current_user.toys[:puzzle]
    )
  end
end

この方法だと引数の数が増えたとき、著しく可読性が落ちそうです

簡単な処理

引数展開を利用します

class BoxesController < ApplicationController
  def new
    @box = ToyBox.new(**user_toys)
  end

  private

  def user_toys
    current_user.toys.slice(:toy_car, :doll, :puzzle)
  end
end

動的にメソッドを決定したい

やりたいこと => 言語設定に合わせて挨拶を変えたい

パラメータが以下のように渡ってきたとする
params = { "language" => "ja" }

最初に思いつく処理

if文で分岐させればいいっしょ!

greeting = Greeting.new

if params[:language] == 'ja'
  puts greeting.message_ja
elsif params[:language] == 'en'
  puts greeting.message_en
elsif params[:language] == 'ch'
  puts greeting.message_ch
end

言うまでもなく、見づらいです。

簡単な処理

sendメソッドを使います

greeting = Greeting.new


puts  greeting.send("message_#{params[:language]}")

最後に

もっとrailsやrubyの良い書き方を知りたいので、よければコメントなどで紹介してください
よろしくおねがいします。

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