Widgets API in Rails

Route, Controller and Views

get '/widgets/:template', to: 'widgets#show'
class WidgetsController < ApplicationController
def show
respond_to do |format|
format.html { render params[:template], layout: 'widgets' }
format.js { render js: js_constructor }
end
end

private
def js_constructor
content = render_to_string(params[:template], layout: false)
"document.write(#{content.to_json})"
end
end
<<%= form_tag send_email_action_url do %>
<%= text_field_tag :name %>
<%= text_field_tag :email %>
<%= text_area_tag :message %>
<%= submit_tag :submit %>
<% end %>

Iframe

<!DOCTYPE html>
<html>
<head><%= stylesheet_link_tag 'widgets', media: 'all' %></head>
<body>
<%= yield %>
<body>
</html>
<iframe src="http://mydomain.com/widgets/contact_form" width="100%" height="100%" frameborder="0"></iframe>

Some important notes about iframes:

  • Browsers are aware that iframes content is served by another domain. So, the same-origin policy applies;
  • Iframes are secure. The same-origin policy prevents scripts to access data from different domains, unless CORS is configured;
  • The content of an iframe is defined by the origin, which includes all the style (css, fonts, js, images, etc.);
  • It is necessary to set the width and height of an iframe. If the iframe’s design is not responsive, you might face difficulties adapting its size in your website.

Inline JavaScript

<script type="text/javascript" src="http://mydomain.com/widgets/contact_form.js"></script>

Some important notes about inline JavaScript:

  • Browsers execute the script from another domain. The script becomes part of the hosting site, and therefore it does not violate the same-origin policy;
  • Inline JavaScript is not secure, as the script might contain an injection attack. So, you must trust the origin of any script;
  • If the script writes HTML code to the DOM, the hosting site’s stylesheet will define the layout of these added elements.

Deciding When to Use Each Approach

--

--

--

Love podcasts or audiobooks? Learn on the go with our new app.

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store
Gabriel Hilal

Gabriel Hilal

More from Medium

Sinatra Base React Project: Game Application

Simulating 500 HTTP status code in Create Tweet API on Twitter

The right way to measure your JS performances

Use Geolocation API to Calculate Distance Between Users (Rails/React JS)