ruby-on-railsrubyreform

How can I create a custom coercion for my Reform form?


I have a form created with Reform gem.

I have a variable that is an array of ids, so the task in to update this variable to be filled with objects from DB.

How can I create custom coercion with dry-types to perform this? I did not find examples of custom types in documentaion.


Solution

  • Reform can use dry-type coercion. This will over-ride the setter, coerce the value and call the original setter. You don't have to create a custom coercion for your use case. See the example below.

    Include following gem in your Gemfile

    gem 'dry-types'
    

    Code below goes into your form class say form.rb

    require 'reform/form/coercion'
    class Form < Reform::Form
      property :ids, type:Types::Coercible::Array.member(Types::Form::Int)
    end