6
10

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

Railsで自分のSNSを表示する

Last updated at Posted at 2016-07-01

SNSを複数登録していて、自分のHPを持っているもしくは作ろうとしている方は、HPに自分の全部のSNSを表示したいと思うかもしれません。

私の場合は必要に駆られて作成したのですが、少しでも上記のような方のお役に立てればと思うので、ソースを以下に記載します。

gem
# instagram表示用
gem 'instagram'

# twitterAPI用
gem 'twitter'

# google+API用
gem 'google-api-client', '0.8'

# Facebook用
gem 'koala'

config > initializers > constants.rbを作成して以下を記入
※『**********』の取得方法は検索エンジンで探せば一杯出てきます。

constants.rb

module Constants
  # facebook
  FB_APP_TOKEN = "**********"
  FB_PAGE_ID = "**********"

  # instagram
  INSTA_USER_ID = "**********"

  # twitter
  TW_CONSUMER_KEY = "**********"
  TW_CONSUMER_SECRET = "**********"
  TW_ACCESS_TOKEN = "**********"
  TW_ACCESS_TOKEN_SECRET = "**********"

  # google+
  GOOGLE_API_KEY = "**********"
  GOOGLE_USER_ID = "**********"

end
contoroller
  require 'twitter'
  require 'google/api_client'

  def index
# facebookの認証・情報取得
    graph = Koala::Facebook::API.new("#{Constants::FB_APP_TOKEN}")
    @me = graph.get_connections("#{Constants::FB_PAGE_ID}", "feed").first(9)

# Instagramの認証・情報取得
    @users = Instagram.user_recent_media("#{Constants::INSTA_USER_ID}", {:count => 9})
    @users.each do |user|
      @image = user.images.low_resolution.url
      @username = user.caption.from.username
      @message = user.caption.text
    end

# twitterの認証・情報取得
    @client = Twitter::REST::Client.new do |config|
      config.consumer_key        = "#{Constants::TW_CONSUMER_KEY}"
      config.consumer_secret     = "#{Constants::TW_CONSUMER_SECRET}"
      config.access_token        = "#{Constants::TW_ACCESS_TOKEN}"
      config.access_token_secret = "#{Constants::TW_ACCESS_TOKEN_SECRET}"
    end

# google+の認証・情報取得
    client = Google::APIClient.new(
    application_name: 'Example Ruby application',
    application_version: '1.0.0'
    )

    client.key = "#{Constants::GOOGLE_API_KEY}"
    client.authorization = nil

    result = client.execute(
    api_method: client.discovered_api(:plus).activities.list,
    parameters: { collection: "public", userId: Constants::GOOGLE_USER_ID }
    )
    @google = result.data
  end
view
# facebook
<ul style="max-width: 930px;margin:auto;overflow: hidden;">
<!-- eachで回して必要なIDを取得してIFRAMEに組み込む -->
    <% @me.each do |feed| %>
      <li style="float:left;width: 300px;height: 400px;margin:3px; border: 2px solid blue; ">
          <% src1 = "https://www.facebook.com/plugins/post.php?href=https%3A%2F%2Fwww.facebook.com%2Fwelleglantz%2Fposts%2F" %>
<!-- 2016.07.13編集分 そもそもiframeにpage_idがなくなった -->
         <% src2 = feed["id"] %>
<!-- 2016.07.13編集分 ここまで -->
         <% src3 = 'min-width="300" height="400" style="border:none;overflow:hidden;margin:3px; border: 2px solid blue scrolling="no" frameborder="0" allowTransparency="true"' %>
        <iframe style="height:100%; width: 100%; max-height: 500px; max-width: 450px;" src=<%= "#{src1}#{src2}#{src3}" %>></iframe>
      </li>
    <% end %>
  <br clear="both"/>
  </ul>

# instagram
<ul style="max-width: 930px;margin:auto;overflow: hidden;">
<!-- eachで回して必要な情報を取得 -->
    <% @users.each do |user| %>
<!-- 画像の有無で取得情報を変更 -->
      <% if user.images.low_resolution.url then %>
        <li style="float:left;width: 300px;height: 400px;margin:3px; border: 2px solid blue; ">
          <%= link_to image_tag(user.images.low_resolution.url, :class => "img- rounded" ), @admin.instagrams_url, :target=>["_blank"] %><br>
          <%= link_to user.caption.from.username, @admin.instagrams_url, :target=>["_blank"] %><br>
          <%= user.caption.text %><br></li>
      <% else %>
        <li style="float:left;width: 300px;height: 400px;margin:3px; border: 2px solid blue; ">
          <%= link_to user.caption.from.username, @admin.instagrams_url, :target=>["_blank"] %><br>
          <%= user.caption.text %><br></li>
      <% end %>
    <% end %>
    <br clear="both"/>
  </ul>

# twitter
  <ul style="max-width: 930px;margin:auto;overflow: hidden;">
    <% @client.home_timeline.first(9).each do |tweet| %>
<!-- 画像の有無で取得情報を変更 -->
      <% if tweet.media[0] then %>
        <li style="float:left;width: 300px;height: 400px;margin:3px; border: 2px solid blue; ">
        <%= link_to image_tag(tweet.media[0].media_url ), @admin.twitter_id, :target=>["_blank"] %><br>
        <%= tweet.user.name + 'さんのツイート : ' %><br>
        <%= tweet.text %><br></li>
      <% else %>
        <li style="float:left;width: 300px;height: 400px;margin:3px; border: 2px solid blue; ">
        <%= tweet.user.name + 'さんのツイート : ' %><br>
        <%= tweet.text %><br></li>
      <% end %>
    <% end %>
  <br clear="both"/>
  </ul>

# google+
  <ul style="max-width: 930px;margin:auto;overflow: hidden;">
<!-- eachで回して必要な情報を取得 -->
    <% @google.items.first(9).each do |item| %>
      <li style="float:left;width: 300px;height: 400px;margin:3px; border: 2px solid blue; ">
<!-- 画像の有無で取得情報を変更 -->
        <% if item.object.attachments[0] then %>
          <% @link = item.url %>
          <% @name = item.actor.displayName %>
          <% @coment = item.title %>
          <% hoge = item.object.attachments[0] %>
          <% fuga = hoge.image %>
          <% if fuga then %>
              <%= link_to image_tag(fuga.url, :class => "img- rounded" ), @link, :target=>["_blank"] %><br>
              <%= link_to @name, @link, :target=>["_blank"] %><br>
              <%= @coment %><br></li>
          <% else %>
            <%= link_to @name, @link, :target=>["_blank"] %><br>
            <%= @coment %><br></li>
          <% end %>
        <% else %>
          <%= link_to @name, @link, :target=>["_blank"] %><br>
          <%= @coment %><br></li>
        <% end %>
    <% end %>
    <br clear="both"/>
  </ul>

これだと全部垂れ流すだけなので、それぞれ最新の1件だけを表示して、画像をクリックしたらSNSの本家に飛ぶようにする場合は下記。

view(2)
<!-- facebook -->
  <div class="allsns">
      <div class="facebook1">
        <% @me.first(1).each do |feed| %>
          <% src1 = "https://www.facebook.com/plugins/post.php?href=https%3A%2F%2Fwww.facebook.com%2Fwelleglantz%2Fposts%2F" %>
<!-- 2016.07.13編集分 -->
         <% src2 = feed["id"] %>
<!-- 2016.07.13編集分 ここまで -->
         <% src3 = 'min-width="300" height="400" style="border:none;overflow:hidden;margin:3px; border: 2px solid blue scrolling="no" frameborder="0" allowTransparency="true"' %>
          <iframe style="height:100%; width: 100%; max-height: 500px; max-width: 450px;" src=<%= "#{src1}#{src2}#{src3}" %>></iframe>
        <% end %>
      </div>

<!-- Instagram -->
      <div class="instagram1">
        <% @users.first(1).each do |user| %>
<!-- 画像の有無で取得情報を変更 -->
          <% if user.images.low_resolution.url then %>
            <%= link_to image_tag(user.images.low_resolution.url, :class => "img- rounded" ), @admin.instagrams_url, :target=>["_blank"] %><br>
            <%= link_to user.caption.from.username, @admin.instagrams_url, :target=>["_blank"] %><br>
            <%= user.caption.text %><br>
          <% else %>
            <%= link_to user.caption.from.username, @admin.instagrams_url, :target=>["_blank"] %><br>
            <%= user.caption.text %>
          <% end %>
        <% end %>
      </div>

<!-- twitter -->
      <div class="twitter1">
        <% @client.home_timeline.first(1).each do |tweet| %>
<!-- 画像の有無で取得情報を変更 -->
          <% if tweet.media[0] then %>
            <%= tweet.user.name + 'さんのツイート : ' %><br>
            <%= tweet.text %><br>
          <% else %>
            <%= tweet.user.name + 'さんのツイート : ' %><br>
            <%= tweet.text %>
          <% end %>
        <% end %>
      </div>

<!-- google+ -->
      <div class="google1">
        <% @google.items.first(1).each do |item| %>
<!-- 画像の有無で取得情報を変更 -->
          <% if item.object.attachments[0] then %>
            <% @link = item.url %>
            <% @name = item.actor.displayName %>
            <% @coment = item.title %>
            <% picture1 = item.object.attachments[0] %>
            <% picture2 = picture1.image %>
            <% if picture2 then %>
                <%= link_to image_tag(picture2.url), @link, :target=>["_blank"] %><br>
                <%= link_to @name, @link, :target=>["_blank"] %><br>
                <%= @coment %><br></div>
            <% else %>
              <%= link_to @name, @link, :target=>["_blank"] %><br>
              <%= @coment %><br>
            <% end %>
          <% else %>
              <%= link_to @name, @link, :target=>["_blank"] %><br>
              <%= @coment %>
          <% end %>
        <% end %>
      </div>
  </div>

styleタグでHTMLに直接見た目を書き込むという暴挙に出ていますが、皆さんはちゃんとCSSで成形してくださいね(^^;)

とりあえず、これで動きます。
表示情報が足りない!という場合は各SNSから帰ってくるJSONを見て、適宜追加してください。
ただし、facebookだけはページのURLを強引に変更しているだけなので、表示する情報を増やすことも減らすこともできません(><)

説明もなくソースを貼っただけの不親切な説明ですが、とりあえず動かしてみて、色々いじると楽しいかもしれません。

追記(2016.07.13)

元々Facebookの投稿は埋め込み用URLを取得して強引に変更して、表示するようにしていました。
いつの間にか埋め込み用URLの書き方が変わっていたので、それに合わせてコードも修正しました。

6
10
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
6
10

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?