Saltar al contenido

¿Cómo incrustar un iframe con ActionText / Trix en Ruby on Rails?

No olvides que en la informática cualquier problema casi siempre tiene diferentes resoluciones, no obstante aquí te mostramos lo más óptimo y mejor.

Solución:

He visto la charla RailsConf2020 sobre Action Text de Chris Oliver, y aquí está la respuesta paso a paso:

_thumbnail.html.erb

app/views/youtubes/_thumbnail.html.erb
<%= image_tag youtube.thumbnail_url, style: "max-width:400px" %>

_youtube.html.erb

app/views/youtubes/_youtube.html.erb

application.js

#packs/application.js
import "youtube"

application.rb

config.to_prepare do
  ActionText::ContentHelper.allowed_tags << "iframe"
end

rutas.rb

  resources :youtube, only: :show

youtube.js

#javascript/youtube.js
import Trix from "trix"
import Rails from "@rails/ujs"

let lang = Trix.config.lang;
Trix.config.toolbar = 
  getDefaultHTML: function() 
    return `
    
` class EmbedController constructor(element) this.pattern = /^https://([^.]+.)?youtube.com/watch?v=(.*)/ this.element = element this.editor = element.editor this.toolbar = element.toolbarElement this.hrefElement = this.toolbar.querySelector("[data-trix-input][name='href']") this.embedContainerElement = this.toolbar.querySelector("[data-behavior='embed_container']") this.embedElement = this.toolbar.querySelector("[data-behavior='embed_url']") this.reset() this.installEventHandlers() installEventHandlers() this.hrefElement.addEventListener("input", this.didInput.bind(this)) this.hrefElement.addEventListener("focusin", this.didInput.bind(this)) this.embedElement.addEventListener("click", this.embed.bind(this)) didInput(event) let value = event.target.value.trim() let matches = value.match(this.pattern) console.log(value,matches) // When patterns are loaded, we can just fetch the embed code if (matches != null) this.fetch(matches[2]) // No embed code, just reset the form else this.reset() fetch(value) Rails.ajax( url: `/youtube/$encodeURIComponent(value)`, type: 'get', error: this.reset.bind(this), success: this.showEmbed.bind(this) ) embed(event) if (this.currentEmbed == null) return let attachment = new Trix.Attachment(this.currentEmbed) this.editor.insertAttachment(attachment) this.element.focus() showEmbed(embed) this.currentEmbed = embed this.embedContainerElement.style.display = "block" reset() this.embedContainerElement.style.display = "none" this.currentEmbed = null document.addEventListener("trix-initialize", function(event) new EmbedController(event.target) )

youtube.rb

#models/youtube.rb
class Youtube
  include ActiveModel::Model
  include ActiveModel::Attributes
  include GlobalID::Identification
  include ActionText::Attachable

  attribute :id

  def self.find(id)
    new(id: id)
  end

  def thumbnail_url
    "http://i3.ytimg.com/vi/#id/maxresdefault.jpg"
  end

  def to_trix_content_attachment_partial_path
    "youtubes/thumbnail"
  end
end

youtube_controller.rb

#controllers/youtube_controller.rb
class YoutubeController < ApplicationController
  def show
    @youtube = Youtube.new(id: params[:id])
    render json: 
      sgid: @youtube.attachable_sgid,
      content: render_to_string(partial: "youtubes/thumbnail", locals:  youtube: @youtube , formats: [:html])
    
  end
end

También disponible aquí: https://gist.github.com/yshmarov/90377ba51f14df09df03e6442cd7412e

Aquí puedes ver las reseñas y valoraciones de los usuarios

¡Haz clic para puntuar esta entrada!
(Votos: 0 Promedio: 0)



Utiliza Nuestro Buscador

Deja una respuesta

Tu dirección de correo electrónico no será publicada. Los campos obligatorios están marcados con *