Custom action initialization

Hello. :wave: I was trying to inject a dependency for my main slice action and was surprised to see that this can’t be done as you’ll get a FrozenError stack dump when an HTTP PUT request is made. Example:

class Update < Main::Action
  def initialize(now: Time.now.utc, **)
    super(**)
    @now = now
  end

  private

  attr_reader :now
end

Is this expected behavior and are you not allowed to inject dependencies even though I’m ensuring all keyword arguments are passed upwards? Is the prescribed way to only inject dependencies via the Deps container?

The documentation – unless I missed something – doesn’t necessarily say this is disallowed so curious to learn more.

Hey @bkuhlmann! We definitely support manual injection of dependencies for Hanami actions.

The thing you’ll need to keep in mind when doing this is that actions freeze themselves in their #initialize, so you’ll just need to assign your instance variables before calling super, e.g.

  def initialize(now: Time.now.utc, **)
    @now = now
    super(**)
  end

Would you mind giving that a try and letting us know how you go?

Thanks!

2 Likes

Hey Tim. :wave: Thanks! :bow: Yep, that solved my issue. Funny – in hindsight – as I should have realized that sooner since the Data class uses similar behavior. :sweat_smile:

1 Like