LoginSignup
155
129

More than 3 years have passed since last update.

Virtusが便利

Last updated at Posted at 2015-04-10

Virtusというgemが便利でした

Railsの検索フォーム等、モデルに紐付かないパラメータを処理する時などに使用するといいと思います。

class SearchForm
  include Virtus.model

  attribute :product_name,    String
  attribute :group_id,        Integer
  attribute :created_at_lteq, Date
  attribute :created_at_gteq, Date
end
# form_param = { product_name: 'hoge', group_id: '111', created_at_lteq: '2015/01/01', created_at_gteq: '2015/04/01' }
form = SearchForm.new(form_params)

form.product_name    # => 'hoge'
form.group_id        # => 111
form.created_at_lteq # => Thu, 01 Jan 2015
form.created_at_gteq # => Wed, 01 Apr 2015

型もちゃんとStringからそれぞれの属性にマッピングしてくれるので、
Date.parse等、面倒な処理をしなくて良い

validation等を追加したい場合、

class SearchForm
  include Virtus.model
  include ActiveModel::Model

  validates :name, presence: true

  ....

ActiveModel::Modelをincludeしてやれば

form.valid?

で簡単に検証できる。楽チンですね。

2018/01/22 追記

何かの値を渡して、初期値を設定したい時、私の場合は、

attribute :code,       String
attribute :from_month, String, default: lambda { |page, attribute| Time.zone.today.strftime('%Y/%m') }
attribute :to_month,   String

def initialize(**args, &block)
  super

  # to_monthが空の場合は、from_monthをset
  self[:to_month] = from_month if to_month.blank? 

  self[:code] = args[:code].presence
end

こんな風に書いたりします。
もっといい方法があるかもしれませんが・・・

Virtus:
https://github.com/solnic/virtus

155
129
3

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
155
129