Chantal
Chantal Software developer focused on personal development not only as a coder but as a human being.

How to share your rails app on Facebook

How to share your rails app on Facebook

A few weeks ago I needed to share my rails app on Facebook and besides a few stackoverflow post i didn’t find anything that blew my mind.

So according to my brief research I found two ways of sharing:

One with the sharer.php link and the second one with FB.ui. In this post we’ll implement the first one and in second post we’ll implement FB.ui. If you are asking yourself why? Simply because I like first to make things work and then we make it better. RED-GREEN-REFACTOR 🤩

Assumptions

  • Basic knowledge of rails is required
  • Basic knowledge of CSS 😀
  • Basic knowledge of js

Things you’ll need

  • A basic rails app with navigation implemented
  • An app on FB

READY? LETS GO!

On your _navbar.html.erb place the link to FB like this:

  #_navbar.html.erb
  
  <%= link_to "<i class='fa fa-facebook'></i>".html_safe, 'https://www.facebook.com/sharer/sharer.php?u=https://your_url', class: 'share', data: { network: 'facebook'} %>

As you can see I’m using html_safe here simply because I’m using font awesome to display my icon, this way the html gets rendered exactly as I want, you can use link_to with a do block and it will have the same effect.

Also don’t forget to add a class we’ll use it to target it with js and finally data network is there in case we want later on to implement other social networks like twitter or Google +

Now on your application.js file lets add the following:

//  FB share dialogue config
$('a.share').click(function(e){
    e.preventDefault();
    var $link   = $(this);
    var href    = $link.attr('href');
    var network = $link.attr('data-network');

    var networks = {
        facebook : { width : 600, height : 300 }
    };

    var popup = function(network){
        var options = 'menubar=no,toolbar=no,resizable=yes,scrollbars=yes,';
        window.open(href, '', options+'height='+networks[network].height+',width='+networks[network].width);
    };

    popup(network);
});

Now what’s happening here:

  1. Target the link with JQUERY
  2. Prevent the normal bevaivor of a link when it gets clicked.
  3. Create the neccesary variables

The network variable gets the inforamtion from our data network hash and it is here where we could add other social networks like Linkedin, Google +, etc. It would look somthing like this

  var networks = {
      facebook : { width : 600, height : 300 },
      twitter  : { width : 600, height : 254 },
      google   : { width : 515, height : 490 },
      linkedin : { width : 600, height : 473 }
  };

What I’m doing is just assigning the size of the popup window and the popup var will generate the width and height according to my specifications inside the network var.

Alrighty, this is all I got for now. Stay tune for the next post where we’ll refactor into the FB.ui

comments powered by Disqus