Facebook commenting w/Rails 4 and Turbolinks - ruby-on-rails

I'm having trouble adding Facebook social plugins (specifically commenting) to my Rails 4 app with Turbolinks enabled. I followed the example on turbolinks issue #62, but couldn't get it to work.
I also tried turbolink's solution here, but couldn't get it to work.
Fixing the apparent typo on the turbolinks page per this answer did not work either.
The SDK isn't loading and there are no errors in the console.
Code:
### view:
<div id="fb-root"></div>
<div class="fb-comments" data-href="<%= request.original_url %>"></div>
### coffeescript:
fb_root = null
fb_events_bound = false
$ ->
loadFacebookSDK()
bindFacebookEvents() unless fb_events_bound
bindFacebookEvents = ->
$(document)
.on('page:fetch', saveFacebookRoot)
.on('page:change', restoreFacebookRoot)
.on('page:load', ->
FB.XFBML.parse()
)
fb_events_bound = true
saveFacebookRoot = ->
fb_root = $('#fb-root').detach()
restoreFacebookRoot = ->
if $('#fb-root').length > 0
$('#fb-root').replaceWith fb_root
else
$('body').append fb_root
loadFacebookSDK = ->
window.fbAsyncInit = initializeFacebookSDK
$.getScript("//connect.facebook.net/en_US/all.js#xfbml=1")
initializeFacebookSDK = ->
FB.init
appId : 'xxxxxxxxxxxx'
channelUrl: '//www.mydomain.com/channel.html'
status : true
cookie : true
xfbml : true
### /public/channel.html
<script src="//connect.facebook.net/en_US/all.js"></script>
--
Thanks. Really appreciate the help.

Try this and let me know if it works...
create a social.js.coffee in assets/javascripts folder.
in it write:
$(document).on 'page:change', ->
FB.init({ status: true, cookie: true, xfbml: true });

Do the following:
Install observejs:
gem 'observejs'
Then add tag to the widget:
<div as="FB" class="fb-comments" data-href="<%= request.original_url %>"></div>
Then create a new script in javascripts folder (fb.coffee in my example):
ObserveJS.bind 'FB', class
root: document.createElement('div')
#::root.id = 'fb-root'
loaded: =>
if !document.body.contains(#root)
document.body.appendChild(#root)
if FB?
FB.XFBML.parse()
else
#initialize()
initialize: =>
js = document.createElement('script')
script = document.getElementsByTagName('script')[0]
js = document.createElement('script')
js.id = 'facebook-jssdk'
js.src = "//connect.facebook.net/en_US/all.js#xfbml=1&appId=YOUR_APP_ID&version=VERSION_OF_API"
script.parentNode.insertBefore(js, script)
Include the js files in your application.js
//= require observejs
//= require fb

Related

Rails Webpacker SCRIPT5009: 'app' is undefined - IE11 issues

For some reason most of my JS work in IE11 and lower fails. No issues with Chrome, Firefox, and Edge.
I have in the application.html.slim file:
meta http-equiv='X-UA-Compatible" content="IE=edge'
I found this: github webpacker thread
So I went through and tried the following in my config > webpack > production.js:
if (environment.plugins.getIndex('UglifyJs') !== -1) {
const plugin = environment.plugins.get('UglifyJs');
plugin.options.uglifyOptions.ecma = 5;
}
environment.config.optimization.minimizer[0].options.uglifyOptions.ecma = undefined
environment.plugins.get("UglifyJs").options.uglifyOptions.ecma = 5
None of those worked. In the console I'm getting:
SCRIPT5009: 'app' is undefined
From my home page I have it set up:
= content_for :head do
= stylesheet_pack_tag 'styles/home'
= javascript_pack_tag 'home'
= javascript_include_tag "//maps.googleapis.com/maps/api/js?key=#{ENV['MAP_KEY']}"
= content_for :body do
.container
.row
#map-banner.banner[type"hidden" data-location=all_locations.to_json]
=render template: '/layouts/application'
javascript:
document.addEventListener('DOMContentLoaded', app.home);
Then in my javascript > packs > home.js
import { mapStyle } from './styles/mapStyle';
app.home = () => {
function init() {
setupSlider();
homeSlider();
startGoogleMap();
let tabs = document.querySelectorAll('a.tab');
for (let tab of tabs) {
tab.addEventListener('click', tabClicked);
}
document
.querySelector('#region-select_')
.addEventListener('change', selectClicked);
}
return init();
};
Current versions:
webpack 3.12.0
rails 5.2.2
yarn 1.17.3
bootstrap 4.3.1
When I checked in the Network on my tiny-slider.js it's returning a status code of 304 however its returning 200 in Chrome. Any idea why it's not compiling?
Leaving this here in case someone finds it useful. Updated config > webpack > environment.js with:
environment.loaders.get('babel').exclude = [];

How to test angular directive that use templateUrl with angular-rails-templates

I'm using teaspoon as the test runner, which load all template files (using angular-rails-templates), which populate the templates module with stuff like this:
angular.module("templates").run(["$templateCache", function($templateCache) {
$templateCache.put("directives/sample/tmpl.html", '<span>Hey</span>')
}]);
And my directive coffee is like this:
angular.module 'myApp'
.directive 'sample', () ->
restrict: 'E'
templateUrl: 'directives/sample/tmpl.html'
scope:
address: "="
controllerAs: 'vm'
bindToController: true
controller: () ->
And my test coffee
describe "sample directive", ->
element = undefined
beforeEach ->
module("myApp", "templates")
# Store references to $rootScope and $compile
# so they are available to all tests in this describe block
beforeEach ->
inject ($compile, $rootScope) ->
scope = $rootScope.$new()
scope.address = "abcdef"
element = $compile("<div><sample address='address'/></div>")(scope)
scope.$digest()
it "Replaces the element with the appropriate content", ->
expect(element.html()).toContain "Hey"
The directive will never render with this. If I replace the templateUrl with template content then it runs fine. But that is not useful at all. What am I missing to let the directive render during test with templateUrl?
You haven't closed the <sample> tag in $compile
Try changing:
element = $compile("<div><sample address='address'</div>")(scope)
To
element = $compile("<div><sample address='address'></sample></div>")(scope)

Select2 custom meessage doesn't work

I'm trying to make a link to create new object when no results were found. I'm using Rails 4. I've included gem gem "select2-rails", added //= require select2 in application.js and
*= require select2
*= require select2-bootstrap
in application.js. Here's my coffeescript which should work fine (ajax working well) but function formatNoMatches seems to do nothing.
$('#invoice_client_id').select2
theme: 'bootstrap'
formatNoMatches: (term) ->
return "<a href='#' onclick='alert('" + term + "');'" + "id='newClient'>Add New Client</a>";
ajax:
url: '/clients.json'
dataType: 'json'
processResults: (data) ->
return {
results: $.map(data, (client, i) ->
{
id: client.id
text: client.name
}
)}
I have found in documentation no mentions of formatNoMatches but in a lot of user examples it's used to do same thing like here.
EDIT
Link or custom text doesn't appear at all.
I looked around a bit and found this way of doing it in the 4.0+ versions.
$('select').select2
language:
noResults: ->
return "<a href='http://google.com'>Add</a>";
escapeMarkup: (markup) ->
return markup;
Let me know if this works for you!

400 Bad Request Request Header Or Cookie Too Large - Rails with facebook and subdomains

I have created application using subdomains in rails 4. It uses Turbolinks. I added a facebook plugin to it. On production, when I refresh the page, everything is ok. However, when I get on the link which uses subdomain, server responds with 400 status code.
400 Bad Request
Request Header Or Cookie Too Large
nginx/1.6.2
As you can see, I use nginx as webserver.
I tried to debug it and noticed, that on my subdomain facebook plugin generates two additional cookies.
When I'll delete those cookies, I can surf on my subdomain freely until I'll go back to root domain. After that, when I'll try to visit my subdomain again, those two cookies are generated again, and whole problem appears once again.
Does anybody know, why this is created and how to prevent facebook of generating it?
It doesn't appears on localhost. I wonder if this is nginx configuration?
My current FB integrations is provided using coffescript.
fb_root = null
fb_events_bound = false
fb_init = ->
loadFacebookSDK()
bindFacebookEvents() unless fb_events_bound
bindFacebookEvents = ->
$(document)
.on('page:fetch', saveFacebookRoot)
.on('page:change', restoreFacebookRoot)
.on('page:load', ->
FB?.XFBML.parse()
)
fb_events_bound = true
saveFacebookRoot = ->
fb_root = $('#fb-root').detach()
restoreFacebookRoot = ->
if $('#fb-root').length > 0
$('#fb-root').replaceWith fb_root
else
$('body').append fb_root
loadFacebookSDK = ->
window.fbAsyncInit = initializeFacebookSDK
$.getScript("//connect.facebook.net/pl_PL/all.js#xfbml=1")
initializeFacebookSDK = ->
FB.init
appId : 'my_app_id'
channelUrl: '//https://facebook.com/my_site
status : true
cookie : true
xfbml : true
#Facebook = { fb_init }
$(document).on "ready page:load pageshow", ->
Facebook.fb_init()
There is a problem in the coffee_script code.
I solved it by copying code from https://developers.facebook.com/docs/plugins/like-button
to the html file right after body tag. This ensured to re-init facebook plugin even if turbolinks where implemented.
Here is the code:
body
#fb-root
javascript:
(function(d, s, id) {
var js, fjs = d.getElementsByTagName(s)[0];
if (d.getElementById(id)) return;
js = d.createElement(s); js.id = id;
js.src = "//connect.facebook.net/pl_PL/sdk.js#xfbml=1&appId=MY_APP_ID&version=v2.0";
fjs.parentNode.insertBefore(js, fjs);
}(document, 'script', 'facebook-jssdk'));

Facebook Koala Gem - Logging Out

I'm having issues logging out using the Koala Gem, and wondering whether they're related.
Below is my Javascript code:
<script>
window.fbAsyncInit = function() {
FB.init({
appId : '310521258992725', // App ID
channelUrl : '//localhost:3000/channel', // Channel File
status : true, // check login status
cookie : true, // enable cookies to allow the server to access the session
xfbml : true // parse XFBML
});
// Additional initialization code here
// whenever the user logs in, we refresh the page
FB.Event.subscribe('auth.login', function() {
setTimeout('document.location.reload()',0);
});
FB.logout(function(response) {
FB.Auth.setAuthResponse(null, 'unknown');
setTimeout('document.location.reload()',0);
});
};
// Load the SDK Asynchronously
(function(d){
var js, id = 'facebook-jssdk', ref = d.getElementsByTagName('script')[0];
if (d.getElementById(id)) {return;}
js = d.createElement('script'); js.id = id; js.async = true;
js.src = "//connect.facebook.net/en_US/all.js";
ref.parentNode.insertBefore(js, ref);
}(document));
</script>
Below is my Facebook tag:
<div id="fb-root"></div>
My logout code:
Logout
The login works perfectly and I can execute api calls no problem. However, after I logout, I get the following error:
OAuthException: Error validating access token: The session is invalid because the user logged out. app/controllers/application_controller.rb:58: in 'fbookinvite_check'
Below is my fbookinvite_check code:
def fbookinvite_check
unless #facebook_cookies.nil?
#access_token = #facebook_cookies["access_token"]
#graph = Koala::Facebook::GraphAPI.new(#access_token)
if !#graph.nil? == true
#friends = #graph.get_object("/me/friends")
end
end
end
The problem seems to be that the cookie is that the access token is invalidated, #graph is not showing as nil after the redirect. If I refresh, then the page loads no problem, but I get the error when I log out.
Perhaps there's a way to catch the #graph.get_object error without shutting down the application?
Any suggestions would be greatly appreciated!!
Yes, just wrap your fbookinvite_check in a begin/rescue where you rescue from OAuthException and then return something sane for your application.
You answered your own question:
Perhaps there's a way to catch the #graph.get_object error without
shutting down the application?
Wrap your logic in a begin/rescue block like so:
def fbookinvite_check
begin
unless #facebook_cookies.nil?
#access_token = #facebook_cookies["access_token"]
#graph = Koala::Facebook::GraphAPI.new(#access_token)
if !#graph.nil? == true
#friends = #graph.get_object("/me/friends")
end
end
rescue OAuthException => ex
# handle the exception if you need to, or just ignore it if thats ok too
end
end

Resources