Video upload in Rails using ActionText

Video upload in Rails using ActionText

A tutorial on how to achieve video upload in Ruby on Rails apps

2022-11-10T00:00:00.000Z


The Problem

I recently wanted to upload videos to my blog, but to my surprise, ActionText with Trix would not enable video playback. The purpose of this tutorial is to show you how to enable video playback in your content. To better understand ActionText, you can check out the documentation here.

Let’s get started.

In ActionText, you will have to understand that every attachment is a blob, located at app/views/active_storage/blobs/_blob.html.erb. In the below partial, we perform a check to confirm if an attachment is a static image or a video and in the case it’s the latter, we will add a video tag with certain parameters.

<figure class="attachment attachment--<%= blob.representable? ? "preview" : "file" %> attachment--<%= blob.filename.extension %>">
    <% if blob.image? %>
        <%`= image_tag blob.representation(resize_to_limit: local_assigns[:in_gallery] ? [ 800, 600 ] : [ 1024, 768 ]) %>
    <% end %>
    <% if blob.video? %>
        <%= video_tag url_for(blob.attachable),
                      preload: "auto",
                      controls: "controls",
                      width: "640",
                      height: "360" %>
    <% end %>

    <figcaption class="attachment__caption">
        <%if caption= blob.try(:caption) %>
        <%= caption %>
        <% else %>
        <span class="attachment__name">
                <%= blob.filename %>
            </span>
        <span class="attachment__size">
                <%= number_to_human_size blob.byte_size %>
            </span>
        <% end %>
    </figcaption>
</figure>

I chose to disable the file size part of the caption, I don’t see it befitting my use case in the blog, it’s a small minor UX improvement.

I used VideoJS for the ability to play video, a cool JavaScript library. You will need to include this in your project. You can include it directly in the app <head> or directly in the resource (e.g. Article) like so:

<link href="https://vjs.zencdn.net/7.8.3/video-js.css" rel="stylesheet" />
<script src="https://vjs.zencdn.net/7.8.3/video.js"></script>`

To further enable this, you will have to enable [SanitizeHelper](https://api.rubyonrails.org/classes/ActionView/Helpers/SanitizeHelper.html) module which provides a set of methods for scrubbing text of undesired HTML elements. These helper methods extend Action View making them callable within your template files.

In your project root directory, run touch config/initializers/html_sanitization.rb and add the following methods:

Rails::Html::WhiteListSanitizer.allowed_tags << "video"
Rails::Html::WhiteListSanitizer.allowed_tags << "source"
Rails::Html::WhiteListSanitizer.allowed_attributes << "controls"

This is all you have to do and baaam... you have video playback option for your video uploads in Rails.