Tracking with google analytics sign up page in Rails with Devise - ruby-on-rails

I am trying to track each page of my Rails application, rendering this partial on the layout:
var analyticsId = '<%= Settings.env.app.analytics_id %>';
(function(i,s,o,g,r,a,m){i['GoogleAnalyticsObject']=r; i[r]=i[r]||function(){
(i[r].q=i[r].q||[]).push(arguments)},i[r].l=1*new Date();a=s.createElement(o),
m=s.getElementsByTagName(o)[0];
a.async=1;a.src=g;m.parentNode.insertBefore(a,m)
})(window,document,'script','https://www.google-analytics.com/analytics.js','ga');
ga('create', '<%= Settings.env.app.analytics_id %>', 'auto', 'trackEvent: true');
ga('send', 'pageview');
After adding the Google Analytics ID to the settings, I can see in my Google Analytics dashboard the visits to my users#sign_in page but not the visits to my users#sign_up page.
Inspecting both pages through the firebug console I see the spected result in the html code:
var analyticsId = 'UA-XXXXXXXX-X';
(function(i,s,o,g,r,a,m){i['GoogleAnalyticsObject']=r;
i[r]=i[r]||function(){
(i[r].q=i[r].q||[]).push(arguments)},i[r].l=1*new Date();a=s.createElement(o),
m=s.getElementsByTagName(o)[0];a.async=1;a.src=g
m.parentNode.insertBefore(a,m)
})(window,document,'script','https://www.google-analytics.com/analytics.js','ga');
ga('create', 'UA-XXXXXXXX-X', 'auto', 'trackEvent: true');
ga('send', 'pageview');
With 'UA-XXXXXXXX-X' = Settings.env.app.analytics_id which is defined in config/settings/app.yml under analytics_id.
We use devise to handle the signin/signup proccess and this is the part related to devise in the routes.rb
Rails.application.routes.draw do
devise_for :users, controllers: {
confirmations: 'users/confirmations',
registrations: 'users/registrations'
}
ActiveAdmin.routes(self)
authenticated :user do
devise_scope :user do
root to: redirect("/home")
end
end
unauthenticated do
devise_scope :user do
root to: redirect("users/sign_in"), as: "unauthenticated_index"
get '/pages/:page', to: 'pages#show', as: "pages_show"
end
end

It seems that the problem was related to the fact that:
Rails 4.0 introduced a feature named Turbolinks to increase the
perceived speed of a website.
Google Analytics doesn’t work for a Rails 4.0 or newer web
applications. To be more precise, it won’t work for all pages. It can
be made to work with a workaround to accommodate Turbolinks.
Making the long story short I have applied a workaround based on the answer in this post:
Google analytics with rails 4

Related

Rails: Server side Google Analytics all trafic in 'Direct' source

I tried several gems for use Server Side GA.
=> Stacato
=> Gabba
=> ...
But I have always the same problem, in google analytics the SOURCE of all my events are in "Direct" (direct traffic), even if i use utm_source, ...
I remarked, each time I trigger an event, Google analytics create a new session with source "Direct" (and a location in United states), and I think the event is attributed to this session and no to my effective session.
My config (with the gem Gem Gabba https://github.com/hybridgroup/gabba ):
View application.html.erb
<script>
(function(i,s,o,g,r,a,m){i['GoogleAnalyticsObject']=r;i[r]=i[r]||function(){
(i[r].q=i[r].q||[]).push(arguments)},i[r].l=1*new Date();a=s.createElement(o),
m=s.getElementsByTagName(o)[0];a.async=1;a.src=g;m.parentNode.insertBefore(a,m)
})(window,document,'script','https://www.google-analytics.com/analytics.js','ga');
ga('create', 'UA-XXXXXXXX-1', 'auto');
ga('send', 'pageview');
</script>
Model User
Gabba::Gabba.new("UA-XXXXXX-1", "mysite.com").event('User', 'Signup', 'Profile completed')
I have a doubt if it's a configuration problem or if it's a recurrent problem when you use a Server Side GA?
Thx #eike & #RaV, you help me to find a solution.
I removed the gabba gem and added staccato gem instead.
The problem was the same (staccato generated a new client_id by default, that's why I had a duplicate), but I figured out how to fix it.
1.Just save the client_id from in the google analytics cookie in your application controller:
before_action :tacking_ga
def client_id
cookies["_ga"].split(".").last(2).join(".")
end
private
def tacking_ga
#tracker = Staccato.tracker('UA-XXXXXXXXX-1', client_id, ssl: true) if Rails.env == "production"
end
2.After that in my controller (example user_controller) I just had to add my event at the right place:
#tracker.event(category: 'User', action: 'Signup', label: "Profile completed", value: nil)
Thx for your help

No route matches [GET] "/users/assets/bootstrap.min.js" only in Firefox?

Firefox gives me this error when i try to sign in or sign up into my app, i am only working locally and i am using devise gem for this. After loading the form it cracks into this routing. The file bootstrap.min.js is in the stylesheets folder and into assets folder. In the layouts i have declared:
<script src="assets/bootstrap.min.js"></script>
Chrome and Safari does not have any problem. Another strange behavoir, i guess related to the same issue, is that when i try to inspect element it falls into this error:
No route matches [GET] "/assets/bootstrap.min.css.map"
The Routes file is done like this:
Rails.application.routes.draw do
resources :properties
devise_for :users
root "properties#index"
get "about" => "pages#about"
get "user_properties" => "pages#user_properties"
get "contact" => "pages#contact"
Anyone have a clue?
try this:
<script src="/assets/bootstrap.min.js"></script>

AngularJS html5mode and rails routes

I have followed all the github issues on HTML5Mode breaking Angular apps in 1.5. I am having the same problem but none of the fixes are working for me.
Im doing the following:
<base href="/">
and
get '/*path', :to => "menus#index"
and
app.config(function($routeProvider, $locationProvider) {
$locationProvider.html5Mode(true);
.when("/users/:u_id/restaurants/:r_id/menus/:m_id/edit", { templateUrl: "/assets/menus/edit.html", controller: "MenuSectionCtrl" })
.when("/users/:u_id/restaurants/:r_id/menus/:m_id/sections/:sec_id/items", { templateUrl: "/assets/menus/items.html", controller: "MenuItemCtrl" })
.when("/users/:u_id/restaurants/:r_id/menus/:m_id/sections/:sec_id/items/:i_id/option_sections", { templateUrl: "/assets/menus/option_sections.html", controller: "MenuOptionSectionCtrl" })
.when("/users/:u_id/restaurants/:r_id/menus/:m_id/sections/:sec_id/items/:i_id/option_sections/:op_sec_id/options", { templateUrl: "/assets/menus/options.html", controller: "MenuOptionCtrl" })
});
I am lost as to what to do next. I have tried every combination of routes and base[href].
Anybody have any ideas?
Also, I have followed this tutorial too. http://omarriott.com/aux/angularjs-html5-routing-rails/
Try this link
http://start.jcolemorrison.com/angularjs-rails-4-1-and-ui-router-tutorial/
If you have mount only single angularjs application then it is very straight forward. You need to make this entry in routes.rb
get '*path' => 'application#index'
And in your application.controller change the index method as below
def index
render layout: 'application'
end
The following link helped me to use rack-rewrite get which seems to work for me. Here is the link. Only the following code in config.ru would allow /api routes to rails:
# config.ru
# This file is used by Rack-based servers to start the application.
use Rack::Rewrite do
rewrite %r{^(?!.*(api|\.)).*$}, '/index.html'
end
require ::File.expand_path('../config/environment', __FILE__)
run Rails.application
I managed to get mine working with:
get '*path', to: redirect('/#/%{path}')
The template I bought was working without hash after the first load but if you refresh the page it does not work. I tried manually adding the hash like /#/page and the above routing does it automatically.

Omniauth facebook - fetch friends

I am trying to configure omniauth-facebook to fetch user friends.
This is my configuration:
ActionController::Dispatcher.middleware.use OmniAuth::Builder do
provider :facebook, "xxxxxx", "xxxxxxxx",
:info_fields => 'friends'
end
I am using Rails 2.3.
I am using this code in view:
<div id="contacts">
</div>
<script type="text/javascript" charset="utf-8">
$('contacts').innerHTML = '<%= request.env['omniauth.auth'].keys %>';
</script>
I am not sure why the script is not being executed, but when I copy:
$('contacts').innerHTML = 'infouidcredentialsextraprovider';
in console after page has loaded it works replacing content of div with that text.
There is no error message in browser console.
Why script does not get executed? I tried with console.log too, and I had no luck.
The info_fields option is still new and so you will have to wait for a new release of the omniauth-facebook gem.
In the meantime, you can try using the master branch by changing your Gemfile to:
gem 'omniauth-facebook', :github => 'mkdynamic/omniauth-facebook'
As for debugging, you can get the information returned from facebook by adding the following as the first line of your callback controller:
raise request.env["omniauth.auth"].to_yaml
Now try to login and you'll be able to take a good look at the hash of nested hashes returned.

How to accept PUT and DELETE methods in my Rails RESTful web service

I've built a Ruby On Rails 3.0.x app that returns JSON. So far, I've got only four methods in my Advertisements controller: index, show, update, destroy.
When I try to call a method from an app within the same domain (through AJAX & jQuery), I succeed. But when I try to do the same from another app within another domain, I get the following error message, only when I try to use the methods PUT and DELETE (it works fine for GET and POST):
XMLHttpRequest cannot load URL_HERE Origin URL_HERE is not allowed by
Access-Control-Allow-Origin.
My RESTful service is called via HTTP, not HTTPS.
Below is the AJAX code that I'm using (16 is the advertisement's id):
$.ajax({
type: "DELETE",
url: "http://SERVICE_URL/advertisements/16.json",
crossDomain: true,
success: function(response){
alert("test");
}
});
Any ideas?
Thanks.
You might try rack-cors. We enable CORS for our web service with:
# config/application.rb
config.middleware.use Rack::Cors do |requests|
requests.allow do |allow|
allow.origins '*'
# perhaps you would stick :put and :delete here?
# then you should follow the rack-cors documentation to only enable it where necessary
allow.resource '*', :headers => :any, :methods => [:get, :post]
end
end

Resources