with_options in rails

I have recently encountered this method, which saved my time and helped me follow the DRY principle

Use case: Consider a scenario, you have a list of trains and you have to apply filters on like depature_time, arrival_time, train_number, arrival_station, depature_station, number of coaches, etc. For that, you have to write interaction. The input will be simple it will have value for mentioned properties or nil.

class FilterTrain < ActiveInteraction
    string :train_name, default: nil
    string :train_code, default: nil
    string :arrival_time, default: nil
    string :depature_time, default: nil
    .....
    .....
end

In this scenario, as we can see default: nil is getting repeated for all inputs, here we can take the help of with_options property to follow the DRY principle

After using with_options

class FilterTrain < ActiveInteraction
  with_options default: nil do
    string :train_name
    string :train_code
    string :arrival_time
    string :depature_time
    .....
    .....
  end
end

With the help of “with_options”, here the “default: nil” property is got applied to all the inputs by writing it only once.

Related Post

Leave a Reply

Your email address will not be published. Required fields are marked *