AaronLasseigne / active_interaction

:briefcase: Manage application specific business logic.
MIT License
2.07k stars 137 forks source link

Document typecasting to HashWithIndifferentAccess #568

Open HashNotAdam opened 9 months ago

HashNotAdam commented 9 months ago

I would like to propose that we add a note to the README that the Hash filter typecasts to HashWithIndifferentAccess.

I was asked to provide support in a case where someone was using interactors as accumulators by mutating the input. While my recommendation would always be to avoid doing this and think more functionally, it was quite jarring to find that even unstripped hashes get typecast. I ended up having to step through the source of ActiveInteraction to understand why their code wasn't working.

For a contrived example:

class SomeInteraction < ActiveInteraction::Base
  array :users

  def execute
    users.each_with_object({}) do |user, users_by_country|
      AccumulatorInteraction.run!(user:, users_by_country:)
    end
  end
end

class AccumulatorInteraction < ActiveInteraction::Base
  object :user
  hash :users_by_country, strip: false

  def execute
    users_by_country[user.country] ||= []
    users_by_country[user.country] << user.id
    users_by_country
  end
end

User = Data.define(:id, :country)
users = [
  User.new(1, "Australia"),
  User.new(2, "Australia"),
  User.new(3, "New Zealand"),
  User.new(4, "Australia"),
  User.new(5, "New Zealand")
].freeze
SomeInteraction.run!(users:) # Output = {}

To be honest, I would prefer if typecasting wasn't performed on objects that are already in the correct type because it's quite jarring to find the variable has been redefined. I am making an assumption, however, that people now rely upon the current behaviour and that would be too breaking of a change. At least, if the unexpected behaviour was documented, it would be simple to debug