Embeddable Javascript widgets

How to create a Github gist-like embeddable widget using Rails

May 22, 2022 2 min read

Github gists example

Github gists are great and easy to share. Simply paste their embed code onto any page.

<!-- Embed code -->
<script src="https://gist.github.com/BrianSigafoos/f0fe5e6417b0acf70ffe1bc6b6498796.js"></script>

The response from that script simply does 2 things using document.write():

  1. Add a stylesheet
  2. Add the HTML tags to render the gist content.
// Endpoint Response to .js code above
  '<link rel="stylesheet" href="https://github.githubassets.com/assets/gist-embed-5687a589e344.css" />'
  '<div id="gist74791356" class="gist">\n <div class="gist-file" translate="no">...</div></div></ div>\n'

Recreating it in Rails

The code to embed the widget is simple:

<div class="demoapp demoapp-widget">
  <script src="http://lvh.me:3000/widgets/mKVEFN.js"></script>
  <p>Widget created with <a href="https://github.com/BrianSigafoos/docker-rails-webpacker-app">Docker Rails Demo App</a> by Brian</p>

And here is a widget rendered below. Note: this only works locally for now via this repo.

Widget created with Docker Rails Demo App by Brian

How it works

Read more posts like this in the Software Engineering Toolbox collection.
Visit homepage
comments powered by Disqus