LoginSignup
0
0

More than 5 years have passed since last update.

RoR|カスタムバリデータを使いまわす

Posted at

やりたいこと

カスタムバリデータを作ったはいいが、まったく関係ないAPIでも同じバリデーションを実行したい。

試してみたこと

APIが呼び出されたらActiveModelを利用して、カスタムバリデータを利用するようにしてみた。

class GreatApiController < ApplicationController
  class FruitApi
    include ActiveModel::Model
    attr_accessor :search_key

    validates :search_key, tel_number: true
  end

  def index
    respond_to do |format|
      fruit_api = FruitApi.new(search_key: params[:search_key])

      if fruit_api.valid?
        format.json { render json: {title: "GreatAPI Response"}, status: 200 }
      else
        format.json { render json: {title: "Error Response"}, status: 500 }
      end
    end
  end
end

TelNumberValidatorが今回の主役です。
本来(?)の用途としては、Bookにあるタイトルには絶対に電話番号(ぽい)ものを入れたいというものです。

class Book < ActiveRecord::Base
  validates :title, tel_number: true
end
class TelNumberValidator < ActiveModel::EachValidator
  def validate_each(record, attribute, value)
    unless value =~ /^\d{2,4}-\d{2,4}-\d{3,4}$/
      record.errors[attribute] << "wrong tel number"
    end
  end
end

やってみて思うこと

カスタムバリデータを利用することでコードがシンプルになっているのはグッド。
ただ、他にももっといい方法があるきがする。。

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