Uploading files with Shrine in Hanami
In almost every web application there is a set of features that are standard and common. Take user registration and authentication, for example. Or commenting system. There’s a pretty big chance you’ll be needing one of these in majority of the applications you create, especially when providing information is one of their goals. Another example of such features is file uploading.
When programming in Rails we are lucky enough that the ecosystem can handle the hassle for us. We have Devise or Sorcery for authentication, Pundit or CanCanCan for authorization, Paperclip or Carrierwave (or even Refile) for file uploading etc. They make less or more assumptions but, unless you are targeting some very specific requirements, they have a huge upside: they work.
Let’s start, then
I suppose you have already generated a scaffold of new Hanami application (type
hanami new hanami-shrine now, if you haven’t), configured database etc. Let’s add a model, repository and a migration to it:
This should all be familiar to you, should you have done any Hanami development before. We also need to add mapping:
Now, let’s add Shrine part. First of all,
The I prefer adding a kind of initializer in
lib/hanami-shrine/image_uploader.rb. You need to include explicit reference to this file on top of the entity and repository (but it’s good to explicitly state dependencies anyway). The contents of the file is Shrine as described in its README. You can leave out
validations: true if you don’t plan to use it.
We also need to alter our entity and repository according to
We are sut up now, so let’s create some controllers. Controller for new action is boring, so I’ll only show the one for create:
And the template for
Nothing here is really surprising, just a standard Hanami constructs. And you might be a little surprised, but that’s it. Of course, you might want to create some other actions, like for example
As I said before, writing your own file upload would not be that difficult, but I suggest you seriously consider using Shrine for that. It gives you a lot of features like validation, file processing etc. with it. And I really would like to see it as a standard. And not only for Hanami, for Rails too.
By the way, I did not show you how to validate the entity. That’s a final bonus for getting that far with reading this blog post:
Thanks for reading and happy uploading!
PS. You can see the complete code in this repository.