AaronLasseigne / active_interaction

:briefcase: Manage application specific business logic.
MIT License
2.06k stars 136 forks source link

Converter object filter doesn't work when default is nil #529

Closed ygaitonde closed 2 years ago

ygaitonde commented 2 years ago
# frozen_string_literal: true

require 'active_interaction'

class Bar
  attr_reader :baz

  def initialize(baz_in)
    @baz = if baz_in.nil?
             400
           else
             baz_in
           end
  end
end

class Foo < ActiveInteraction::Base
  object :x, class: Bar, converter: :new, default: nil

  def execute
    x
  end
end

# expect 400
puts Foo.run!.baz

# expect 5
puts Foo.run!(x: 5).baz

This code doesn't try and cast nil, and instead just sets the object to nil, causing a NoMethodError when we expect 400 to be printed.

From the docs: The value given to the default option will also be converted.

Happy to take a stab at fixing this.

AaronLasseigne commented 2 years ago

This could probably be more clear in the documentation but nil is a special case that doesn't pass through. Giving a default value of nil is how a filter is made optional. What you want is:

class Foo < ActiveInteraction::Base
  object :x, class: Bar, converter: :new, default: Bar.new(nil)

  def execute
    x
  end
end
AaronLasseigne commented 2 years ago

I'll update the docs to clarify.