4

This is probably a terribly simple question but i can't figure out how to render an embedded tweet.

For simplicity, this is my controller:

class TweetsController < ApplicationController

  def index

  @tweet = twitter_client.oembed('527501479142109184')

  end

end

And in the view if i just do the following it displays the object only:

<%= @tweet %>

i.e. #<Twitter::OEmbed:0x007fb878abc5d8>

On inspection this gives:

#<Twitter::OEmbed:0x007fb875cacd28 @attrs={:cache_age=>"3153600000", :url=>"https://twitter.com/HuayuanSong/statuses/527501479142109184", :height=>nil, :provider_url=>"https://twitter.com", :provider_name=>"Twitter", :author_name=>"Huayuan Song", :version=>"1.0", :author_url=>"https://twitter.com/HuayuanSong", :type=>"rich", :html=>"<blockquote class=\"twitter-tweet\"><p>Jeg kunne lide en video på <a href=\"https://twitter.com/YouTube\">@YouTube</a> <a href=\"http://t.co/hhhTvyJA6y\">http://t.co/hhhTvyJA6y</a> Obama: U.S. leading the way against Ebola spread</p>&mdash; Huayuan Song (@HuayuanSong) <a href=\"https://twitter.com/HuayuanSong/status/527501479142109184\">October 29, 2014</a></blockquote>\n<script async src=\"//platform.twitter.com/widgets.js\" charset=\"utf-8\"></script>", :width=>550}>

Obviously, this is terribly simple and i'm just using this a proof of concept type thing. Can somebody explain how i go from having the object to being able to display the actual embedded tweet?

thanks

Robbo
  • 1,292
  • 2
  • 18
  • 41

1 Answers1

6

Simply calling @tweet will just reference the object. In order to display the tweet you will want to call:

<%= raw(@tweet.html) %>

Also, from Twitter's documentation:

The returned HTML snippet will be automatically recognized as an Embedded Tweet when Twitter’s widget JavaScript is included on the page.

The Javascript snippet looks like this:

<script>
window.twttr = (function (d, s, id) {
var t, js, fjs = d.getElementsByTagName(s)[0];
if (d.getElementById(id)) return;
js = d.createElement(s); js.id = id;
js.src= "https://platform.twitter.com/widgets.js";
fjs.parentNode.insertBefore(js, fjs);
return window.twttr || (t = { _e: [], ready: function (f) { t._e.push(f) } });
}(document, "script", "twitter-wjs"));
</script>
Joel Brewer
  • 1,622
  • 19
  • 30
  • great thanks, that makes sense, silly to miss that. However, now all that is displayed is the html? I have the widget.js script included in my `application.html.erb` template before the closing `

    ` tag

    – Robbo Oct 29 '14 at 18:01
  • Try using the [raw helper method](http://apidock.com/rails/ActionView/Helpers/RawOutputHelper/raw): `<%= raw(@tweet.html) %>` – Joel Brewer Oct 29 '14 at 18:08