Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Document typecasting to HashWithIndifferentAccess #568

Open
HashNotAdam opened this issue Dec 14, 2023 · 0 comments
Open

Document typecasting to HashWithIndifferentAccess #568

HashNotAdam opened this issue Dec 14, 2023 · 0 comments

Comments

@HashNotAdam
Copy link

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

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant