Search code examples
ruby-on-railsrails-activestoragetrixactiontext

Acton text, display video player with active storage


I am using Trix editor with upload attachments functionality.

At the moment I can upload images, pdf, videos, etc... and show them after submit. Also I can have an image preview of what I uploaded.

But I don't know how to add a video player to it.

My actual _blob.html.erb looks like this:

<figure class="attachment attachment--<%= blob.representable? ? "preview" : "file" %> attachment--<%= blob.filename.extension %>">
    <% if blob.representable? %>
    <%= image_tag blob.representation(resize_to_fit: local_assigns[:in_gallery] ? [ 800, 600 ] : [ 1024, 768 ]) %>
    <% end %>

    <figcaption class="attachment__caption flex-1">
        <div>
        <% if caption = blob.try(:caption) %>
        <%= caption %>
        <% else %>
        <span class="attachment__name text-gray-600"><%= blob.filename %></span>
        <span class="attachment__size text-gray-600"><%= number_to_human_size blob.byte_size %></span>
        <% end %>
        </div>
         <div class="mt-6 mb-4">
        <%= link_to "View file", rails_blob_url(blob, disposition: "preview"), target: "_blank", class: "bg-gray-200 text-sm py-2 px-4 rounded mt-6" %> -
        <%= link_to "Download", rails_blob_path(blob, disposition: "attachment"), class: " text-sm bg-gray-200 py-2 px-4 rounded" %>
        </div>
    </figcaption>
</figure>

Solution

  • in your _blob:

     - if blob.video?
        %video(controls="true" width="100%" preload="metadata")
          %source{src: rails_blob_url(blob), type:"#{blob.content_type}"}
    

    %video is the HTML5 video tag

    Next you will need to add this to application.rb:

    #video previews for action_text
    config.after_initialize do
      ActionText::ContentHelper.allowed_attributes.add 'style'
      ActionText::ContentHelper.allowed_attributes.add 'controls'
    
      ActionText::ContentHelper.allowed_tags.add 'video'
      ActionText::ContentHelper.allowed_tags.add 'audio'
      ActionText::ContentHelper.allowed_tags.add 'source'
    end
    

    The above works for rails 6.0.1 but might not work with rails 6.0.3