Allowing a url with multiple formats

Hi!

I’m new to Hanami. I’m trying to convert a Rails application over to a Hanami application. In the rails app we have a health page that can be viewed in either html or json.

I have implemented that as two actions, but I am guessing there might be a better way.

What would be the Hanami way to implement show both formats?

Also I want to share the logic for the data. I put the shared logic in the view, but I am guessing that was also not quite right. Where should the shared logic go?

Thanks for your help and feedback!

Carolyn

Hi there! Thanks for giving Hanaami a spin.

I forked your repo and I was able to combine the two actions into one: at /health

See me work here:

I’ll work to update the docs to illustrate this use case, since it’s a common one.

I started working on getting health.json to go to the same endpoint as well, but I don’t have time to finish it right now.

And yes, your intuition is right that the actions should not include a Deps from a view. That inverts the dependency graph in a messy way. An action automatically renders a view (for HTML, when you directly set response.body, it doesn’t do that).

As for a better way to do it: I’d make a Status domain object (with Data.define personally but a Plain Old Ruby class is fine) that the OrcidAPIStatus operation returns, instead of serializing to JSON from that operation. Then, I’d serialize that in the action to JSON, and the HTML view can access the Status domain object directly in the view (passed from the action). I’ll work on this later, to fully illustrate what I mean as an example for others, as well.

I thought I should be able to do what you have shown, but could not quite get it to work.

For the domain object where would that live? Is it something like an Operation? I added the service folder for some POROs that we had in our Rails app, but I have been trying to exercise the “correct” concepts in Hanami.

I’m excited to see the complete example.

As you can see my Rails app and Subsequent Hanami app will be open source, so if you like they can be utilized by the community for an example conversion (assuming I succeed). I also did a test migration, which may also be helpful (If I did it correctly).

1 Like