Skip to content

Instantly share code, notes, and snippets.

@dchymko
Last active April 5, 2017 00:28
Show Gist options
  • Save dchymko/1f9d3bd08540ca7b263caab8246ef545 to your computer and use it in GitHub Desktop.
Save dchymko/1f9d3bd08540ca7b263caab8246ef545 to your computer and use it in GitHub Desktop.
Coding Fundamentals W05D01 connecting 2 Finstagram apps together

Linking two Finstagram apps

First thing you will need to decide is who will be the api and who will be the consumer.

Changes the api person needs to make

Change their project to be public instead of private (In the Cloud 9 Project settings)

Add a new route to provide the data in json format:

get '/api/posts/json' do
  json(Post.all())
end

Change the post.rb moel to override the default to_json method:

  def as_json(options)
    super(:include => [:user, :comments, :likes], 
    :methods => [:comment_count, :like_count, :humanized_time_ago])
  end

Changes the consumer person needs to make

Add the rest-client gem to your Gemfile: gem 'rest-client'

You will need to run bundle install in the console and then restart your ruby app after doing this

Add a reference to the new gem at the top of your actions.rb require 'rest-client

Add a new route (in actions.rb) to view the posts from the other server. Make sure you replace the <something else> URL with the URL of the api persons project:

get '/remoteposts' do
  @posts = []
  data = RestClient.get ('https://<something else>.c9users.io')
  @posts = JSON.parse(data)
  erb :remoteposts
end

Create a remoteposts.erb file that will dislay the data that was obtained fromthe API instead of your local database (ActiveRecord). Since this data is cometing through as a hash obect instead of ActiveRecord objects, we have to use the "old" style of referencing objects that you did before changing to ActiveRecord:


<main role="main">
  <% @posts.each do |post| %>
    <article class="post">
      <div class="user-info">
        <img src="<%= post["avatar_url"] %>" alt="<%= post["username"] %>">
        <h2><%= post["username"] %></h2>
        <h3><%= post["humanized_time_ago"] %></h3>
      </div>
      <a class="photo" href="#">
        <img src="<%= post["photo_url"] %>" alt="post from <%= post["username"] %>">
      </a>
      <div class="actions">
        <%= post["like_count"] %> likes
        <span class="comment-count"><%= post["comment_count"] %> comment</span>
      </div>
      
    </article>
  <% end %>
</main>

Now you should be able to go to your app url with /remoteposts and see pists from the other persons app. Have the add a new post and refresh your page to see if it shows up. Cool stuff!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment