I've got a Rails 4.2 app that I've deployed with Heroku and I've tried to add Google Analytics to it. However, Google Analytics isn't picking up any sessions.
Any suggestions why and how to resolve this?
CODE
/app/layouts/_footer.html.erb:
<% if Rails.env.production? %>
<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','//www.google-analytics.com/analytics.js','ga');
ga('create', 'UA-XXXXXXXX-X', 'herokuapp.com');
ga('send', 'pageview');
</script>
<% end %>
/app/layouts/application.html.erb:
<!DOCTYPE html>
<html>
<head>
<title>Title</title>
<%= Gon::Base.render_data({}) %>
<%= stylesheet_link_tag 'application', media: 'all', 'data-turbolinks-track' => true %>
<%= javascript_include_tag 'application', 'data-turbolinks-track' => true %>
<%= csrf_meta_tags %>
<meta name="viewport" content="width=device-width, initial-scale=1.0">
</head>
<body>
<div class="container">
<%= yield %>
</div>
<%= render 'layouts/footer' %>
</body>
</html>
/app/assets/javascripts/analytics.js.coffee:
$(document).on 'page:change', ->
if window._gaq?
_gaq.push ['_trackPageview']
else if window.pageTracker?
pageTracker._trackPageview()
/app/assets/javascripts/application.js:
//= require jquery
//= require analytics
//= require bootstrap
//= require jquery_ujs
//= require jquery.ui.all
//= require Chart
//= require jquery.turbolinks
//= require lodash
//= require_tree .
Gemfile:
source 'https://rubygems.org'
gem 'rails', '4.2.2'
gem 'bootstrap-sass', '3.2.0.0'
gem 'sass-rails', '5.0.2'
gem 'uglifier', '2.5.3'
gem 'coffee-rails', '4.1.0'
gem 'jquery-rails', '4.0.3'
gem 'jquery-ui-rails', '~> 4.2.1'
gem 'turbolinks', '2.3.0'
gem 'jquery-turbolinks'
gem 'jbuilder', '2.2.3'
gem 'sdoc', '0.4.0', group: :doc
gem 'chart-js-rails'
gem 'gon'
gem 'lodash-rails'
group :development, :test do
gem 'sqlite3', '1.3.9'
gem 'byebug', '3.4.0'
gem 'web-console', '2.0.0.beta3'
gem 'spring', '1.1.3'
end
group :production do
gem 'pg', '0.17.1'
gem 'rails_12factor', '0.0.2'
end
The way you are adding your script is the wrong way, since it will not work due to Turbolinks, you know the code you have in your _footer won't be running as expected since that piece of markup won't reload because of Turbolinks.
I will give you my custom implementation of google analytics for all my rails apps.
In your app/assets/javascripts create a new file called google_analytics.js.coffee and add the following script:
class #GoogleAnalytics
#load: ->
# Google Analytics depends on a global _gaq array. window is the global scope.
window._gaq = []
window._gaq.push ["_setAccount", GoogleAnalytics.analyticsId()]
# Create a script element and insert it in the DOM
ga = document.createElement("script")
ga.type = "text/javascript"
ga.async = true
ga.src = ((if "https:" is document.location.protocol then "https://ssl" else "http://www")) + ".google-analytics.com/ga.js"
firstScript = document.getElementsByTagName("script")[0]
firstScript.parentNode.insertBefore ga, firstScript
# If Turbolinks is supported, set up a callback to track pageviews on page:change.
# If it isn't supported, just track the pageview now.
if typeof Turbolinks isnt 'undefined' and Turbolinks.supported
document.addEventListener "page:change", (->
GoogleAnalytics.trackPageview()
), true
else
GoogleAnalytics.trackPageview()
#trackPageview: (url) ->
unless GoogleAnalytics.isLocalRequest()
if url
window._gaq.push ["_trackPageview", url]
else
window._gaq.push ["_trackPageview"]
window._gaq.push ["_trackPageLoadTime"]
#isLocalRequest: ->
GoogleAnalytics.documentDomainIncludes "local"
#documentDomainIncludes: (str) ->
document.domain.indexOf(str) isnt -1
#analyticsId: ->
# your google analytics ID(s) here...
'UA-xxxxxxxx-x'
GoogleAnalytics.load()
As you can see it adds support for Turbolinks, this is a clean and better way to add Google analytics to your app. Hope it works for you.
Related
Receiving an error (ExecJS::ProgramError in Pages#home) when I run rails server and load my page after I install bootstrap 4 ruby gem.
Completely new to Ruby on rails and largely programming so bear with me. I'm running through the One month rails tutorial (https://onemonth.com/courses/rails/curriculum) and hitting a sticking point at the installing bootstrap 4 point. I'm using windows 10 vs Mac OS for the tutorial.
I've tried running through the same directions for installing bootstrap 4 as the course uses (https://www.diycode.cc/projects/twbs/bootstrap-rubygem) as well as the latest directions (https://github.com/twbs/bootstrap-rubygem). I get the same error either way, but my latest attempt runs through the steps below.
Steps
Add bootstrap to your Gemfile:
gem 'bootstrap', '~> 4.2.1'
bundle install
Import Bootstrap styles in app/assets/stylesheets/application.scss:
// Custom bootstrap variables must be set or imported *before* bootstrap.
#import "bootstrap";
renamed application.css to application.scss in app/assets/stylesheets/
add the jquery-rails gem to your Gemfile:
gem 'jquery-rails'
bundle install
Add Bootstrap dependencies and Bootstrap to your application.js:
//= require jquery3
//= require popper
//= require bootstrap-sprockets
I've also tried removing
gem 'duktape'
from my gemfile as has been suggested elsewhere but had no luck.
Gemfile
git_source(:github) { |repo| "https://github.com/#{repo}.git" }
ruby '2.3.3'
gem 'rails', '~> 5.2.2'
gem 'sqlite3'
gem 'puma', '~> 3.11'
gem 'sass-rails', '~> 5.0'
gem 'uglifier', '>= 1.3.0'
gem 'duktape'
gem 'coffee-rails', '~> 4.2'
gem 'turbolinks', '~> 5'
gem 'jbuilder', '~> 2.5'
gem 'jquery-rails'
gem 'bootsnap', '>= 1.1.0', require: false
gem 'bootstrap', '~> 4.2.1'
group :development, :test do
gem 'byebug', platforms: [:mri, :mingw, :x64_mingw]
end
group :development do
gem 'web-console', '>= 3.3.0'
end
group :test do
gem 'capybara', '>= 2.15'
gem 'selenium-webdriver'
gem 'chromedriver-helper'
end
gem 'tzinfo-data', platforms: [:mingw, :mswin, :x64_mingw, :jruby]
application.scss
// Custom bootstrap variables must be set or imported *before* bootstrap.
#import "bootstrap";
application.js
//= require jquery3
//= require popper
//= require bootstrap-sprockets
//= require rails-ujs
//= require activestorage
//= require turbolinks
//= require_tree .
pages_controller.rb
class PagesController < ApplicationController
def home
end
end
application_controller.rb
class ApplicationController < ActionController::Base
end
home.html.erb
<h1>Welcome to my website!</h1>
<p>Sign up here</p>
<p>Teams</p>
<p>Standings</p>
<p>Schedules</p>
<p>Stats</p>
When I run rails server the page comes up saying "ExecJS::ProgramError in Pages#home"
Showing C:/omrails/app/views/layouts/application.html.erb where line #8 raised:
undefined not callable
Rails.root: C:/omrails
(execjs):1
app/views/layouts/application.html.erb:8:in `_app_views_layouts_application_html_erb__882755417_31415124'
My code in views/layouts/application.html.erb looks as follows:
<!DOCTYPE html>
<html>
<head>
<title>One Month Rails</title>
<%= csrf_meta_tags %>
<%= csp_meta_tag %>
<%= stylesheet_link_tag 'application', media: 'all', 'data-turbolinks-track': 'reload' %>
<%= javascript_include_tag 'application', 'data-turbolinks-track': 'reload' %>
</head>
<body>
<%= link_to "Home", root_path %>
<%= link_to "About", about_path %>
<%= link_to "Contact us", contact_path %>
<%= yield %>
</body>
</html>
I am trying to use the jQuery datepicker function but I am receiving an error Uncaught type error: $(...).datepicker() is not a function. I have gone through my files and do not see a double reference to jQuery or incorrect file order in the application.js. Could someone help point out what might be the problem?
application.html.erb
<!DOCTYPE html>
<html>
<head>
<%= javascript_include_tag 'application' %>
<title>MyApp</title>
<meta name="viewport" content="width=device-width, initial-scale=1">
<!-- CSS/Bootstrap -->
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" integrity="sha384-1q8mTJOASx8j1Au+a5WDVnPi2lkFfwwEAa8hDDdjZlpLegxhjVME1fgjWPGmkzs7" crossorigin="anonymous">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap-theme.min.css" integrity="sha384-fLW2N01lMqjakBkx3l/M9EahuwpSfeNvV63J5ezn3uZzapT0u7EYsXMjQV+0En5r" crossorigin="anonymous">
<%= stylesheet_link_tag 'application' %>
<%= csrf_meta_tags %>
<!-- -->
</head>
<body>
<%= render partial: "shared/top_info" %>
<%= yield %>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js" integrity="sha384-0mSbJDEHialfmuBBQP6A4Qrprq5OVfW37PRR3j5ELqxss1yVqOtnepnHVP9aJ7xS" crossorigin="anonymous">
</script>
<!-- -->
</body>
</html>
application.js
//= require jquery
//= require jquery_ujs
//= require ahoy
//= require_tree .
$('#customer_drop_off_date').datepicker();
html.erb
<% form_tag('/post') do %>
<%= text_field_tag(:customer_drop_off_date) %>
<% end %>
Gemfile
source 'https://rubygems.org'
gem 'rails', '4.2.6'
gem 'pg', '~> 0.15'
gem 'uglifier', '>= 1.3.0'
gem 'jquery-rails'
gem 'jbuilder', '~> 2.0'
gem 'sprockets'
gem 'sdoc', '~> 0.4.0', group: :doc
gem 'bcrypt', '~> 3.1.7'
gem 'devise'
gem 'figaro'
gem 'paperclip', '~> 5.0.0.beta1'
gem 'ahoy_matey'
gem 'geocoder'
group :development, :test do
gem "pry"
gem "pry-rails"
gem "pry-stack_explorer"
gem "pry-byebug"
gem 'byebug'
end
group :development do
gem 'web-console', '~> 2.0'
gem 'spring'
end
Include gem 'jquery-ui-rails' into your gemfile.
To require all jQuery UI modules, add the following to your application.js:
//= require jquery-ui
Into your stylesheets:
/*
*= require jquery-ui
*/
Gem docs
Using https://github.com/TrevorS/bootstrap3-datetimepicker-rails
In Gemfile:
gem 'momentjs-rails', '>= 2.9.0'
gem 'bootstrap3-datetimepicker-rails', '~> 4.17.37'
Run:
bundle
Bootstrap CSS options (choose one):
CDN in .erb as shown in question
Rails Asset Pipeline https://github.com/seyhunak/twitter-bootstrap-rails
Install into vendor/assets/ as described here: http://www.erikminkel.com/2013/09/01/twitter-bootstrap-3-in-a-rails-4-application
In application.css after bootstrap require:
*= require bootstrap-datetimepicker
In application.js:
//= require jquery
//= require jquery_ujs
//= require ahoy
//
// NEW (add these two lines)
//= require moment
//= require bootstrap-datetimepicker
//
//= require_tree .
// OLD
//$('#customer_drop_off_date').datepicker();
// NEW
$('#customer_drop_off_date').datetimepicker();
First of all, this is not a duplicate! It's the same 'not defined' error but follows exactly the github (https://github.com/reactjs/react-rails) guide and still not working
Gemfile:
gem 'rails'
gem 'pg', '~> 0.15'
gem 'sass-rails'
gem 'uglifier'
gem 'coffee-rails'
gem 'therubyracer'
gem 'bootstrap-sass'
gem 'jquery-rails'
gem 'jquery-ui-rails'
gem 'font-awesome-sass'
gem 'sprockets-rails'
gem 'react-rails'
gem 'turbolinks'
gem 'jbuilder', '~> 2.0'
gem 'sdoc', '~> 0.4.0', group: :doc
application.js:
//= require jquery
//= require jquery_ujs
//= require jquery-ui
//= require bootstrap-sprockets
//= require react
//= require react_ujs
//= require components
application.html:
<!DOCTYPE html>
<html>
<head>
<title>project</title>
<%= stylesheet_link_tag 'application', media: 'all' %>
<%= javascript_include_tag 'application' %>
<%= javascript_include_tag 'react' %>
<%= csrf_meta_tags %>
</head>
<body>
components/app.js.jsx:
// var React = window.ReactRailsUJS;
var Hello = React.createClass({
render: function() {
return (
<p>Hello</p>
);
}
});
ReactDOM.render(
<Hello />,
document.getElementById("react-msg")
);
console.log(1);
html file:
<style type="text/css">
h1, h3 {
font-weight: bold;
}
</style>
<div class="container">
<h1>React JS</h1>
<h3 id="react-msg"></h3>
</div>
development.rb:
Rails.application.configure do
...
# config/environments/development.rb
config.react.variant = :development
# to include react add-ons
config.react.addons = true # defaults to false
end
When I visit the page it says
ReferenceError: React is not defined
What I did wrong?
If I uncomment the following
var React = window.ReactRailsUJS;
it says createClass is not a function and same for every other React function
For anyone that runs onto this issue and lands here, apparently it is a problem beginning with version 16 onward of React. The reason is cause React.createClass is deprecated. Instead, you're supposed to use createReactClass.
Much of the (now old) documentation provided an example like this:
var HelloMessage = React.createClass({
render: function() {
return (
<h1>Hello {this.props.name}!</h1>
)
}
});
Instead, you should use this:
var HelloMessage = createReactClass({
render: function() {
return (
<h1>Hello {this.props.name}!</h1>
)
}
});
I can only assume they didn't update their examples, and many of them are still showing up when you search for react-rails as of Nov-2017.
I've been trying to connect bootstrap framework to my project by following this documentation and I can't set it up for some reason.
Why is it?
assets/stylesheets/application.scss
/*
* This is a manifest file that'll be compiled into application.css, which will include all the files
* listed below.
*
* Any CSS and SCSS file within this directory, lib/assets/stylesheets, vendor/assets/stylesheets,
* or any plugin's vendor/assets/stylesheets directory can be referenced here using a relative path.
*
* You're free to add application-wide styles to this file and they'll appear at the bottom of the
* compiled file so the styles you add here take precedence over styles defined in any styles
* defined in the other CSS/SCSS files in this directory. It is generally better to create a new
* file per style scope.
*
#import "bootstrap-sprockets";
#import "bootstrap";
*
*= require bootstrap3-editable/bootstrap-editable
*= require_tree .
*= require_self
*/
assets/javascripts/application.js
// This is a manifest file that'll be compiled into application.js, which will include all the files
// listed below.
//
// Any JavaScript/Coffee file within this directory, lib/assets/javascripts, vendor/assets/javascripts,
// or any plugin's vendor/assets/javascripts directory can be referenced here using a relative path.
//
// It's not advisable to add code directly here, but if you do, it'll appear at the bottom of the
// compiled file.
//
// Read Sprockets README (https://github.com/rails/sprockets#sprockets-directives) for details
// about supported directives.
//
//= require jquery
//= require jquery_ujs
//= require turbolinks
//= require bootstrap
//= require bootstrap3-editable/bootstrap-editable
//= require_tree .
views/layouts/application.html.erb
<!DOCTYPE html>
<html>
<head>
<title>Greenbull</title>
<%= stylesheet_link_tag 'application', media: 'all', 'data-turbolinks-track' => true %>
<%= javascript_include_tag 'application', 'data-turbolinks-track' => true %>
<%= csrf_meta_tags %>
</head>
<body>
<div id="container">
<div id="user_header">
<% if current_user %>
Logged in as <%= current_user.full_name %>
<%= link_to "Log Out", logout_path("current"), method: 'delete' %><br />
<p><%= link_to "My tasks", user_tasks_path(current_user) %>
<% else %>
<%= link_to "Sign Up", signup_path %> or
<%= link_to 'Log In', login_path %>
<% end %>
</div>
<% flash.each do |message_type, message| %>
<div class="flash-<%= message_type %>"><%= message %></div>
<% end %>
<%= yield %>
</body>
</html>
Gemfile
source 'https://rubygems.org'
group :development, :test do
gem 'rspec-rails', '~> 3.0'
end
# Bundle edge Rails instead: gem 'rails', github: 'rails/rails'
gem 'rails', '4.2.3'
# Use sqlite3 as the database for Active Record
gem 'sqlite3'
# Use SCSS for stylesheets
gem 'sass-rails', '~> 5.0'
# Use Uglifier as compressor for JavaScript assets
gem 'uglifier', '>= 1.3.0'
# Use CoffeeScript for .coffee assets and views
gem 'coffee-rails', '~> 4.1.0'
# See https://github.com/rails/execjs#readme for more supported runtimes
# gem 'therubyracer', platforms: :ruby
# Use jquery as the JavaScript library
gem 'jquery-rails'
# Turbolinks makes following links in your web application faster. Read more: https://github.com/rails/turbolinks
gem 'turbolinks'
# Build JSON APIs with ease. Read more: https://github.com/rails/jbuilder
gem 'jbuilder', '~> 2.0'
# bundle exec rake doc:rails generates the API under doc/api.
gem 'sdoc', '~> 0.4.0', group: :doc
# Use ActiveModel has_secure_password
# gem 'bcrypt', '~> 3.1.7'
# Use Unicorn as the app server
# gem 'unicorn'
# Use Capistrano for deployment
# gem 'capistrano-rails', group: :development
group :development, :test do
# Call 'byebug' anywhere in the code to stop execution and get a debugger console
gem 'byebug'
# Access an IRB console on exception pages or by using <%= console %> in views
gem 'web-console', '~> 2.0'
# Spring speeds up development by keeping your application running in the background. Read more: https://github.com/rails/spring
gem 'spring'
gem 'bcrypt'
gem 'pry'
gem 'pg'
gem 'bootstrap-x-editable-rails'
gem 'bootstrap-sass'
end
I have installed bootstrap-sass 3.3.5.1, sass-rails 5.0.3.
Any help?
Read the instructions of the bootstrap-sass gem and follow their conventions https://github.com/twbs/bootstrap-sass.
Import Bootstrap styles in app/assets/stylesheets/application.scss:
// "bootstrap-sprockets" must be imported before "bootstrap" and "bootstrap/variables"
#import "bootstrap-sprockets";
#import "bootstrap";
I am unable to get bootstrap to work in my layout, I can't seem to figure out why. I did rm app/assets/stylesheets/application.css
Any help would be much appreciated.
Gemfile
source 'https://rubygems.org'
ruby '2.1.2'
# Bundle edge Rails instead: gem 'rails', github: 'rails/rails'
gem 'rails', '4.2.0.beta2'
# Use postgresql as the database for Active Record
gem 'pg'
gem 'rails_12factor', group: :production
gem 'bootstrap-sass', '~> 3.2.0'
gem 'autoprefixer-rails'
# Use SCSS for stylesheets
gem 'sass-rails', '~> 5.0.0.beta1'
# Use Uglifier as compressor for JavaScript assets
gem 'uglifier', '>= 1.3.0'
# Use CoffeeScript for .js.coffee assets and views
gem 'coffee-rails', '~> 4.0.0'
# See https://github.com/sstephenson/execjs#readme for more supported runtimes
# gem 'therubyracer', platforms: :ruby
# Use jQuery as the JavaScript library
gem 'jquery-rails', '~> 4.0.0.beta2'
# Turbolinks makes following links in your web application faster. Read more: https://github.com/rails/turbolinks
gem 'turbolinks'
# Build JSON APIs with ease. Read more: https://github.com/rails/jbuilder
gem 'jbuilder', '~> 2.0'
# bundle exec rake doc:rails generates the API under doc/api.
gem 'sdoc', '~> 0.4.0', group: :doc
# Use ActiveModel has_secure_password
# gem 'bcrypt', '~> 3.1.7'
# Use Unicorn as the app server
# gem 'unicorn'
# Use Capistrano for deployment
# gem 'capistrano-rails', group: :development
group :development, :test do
# Call 'debugger' anywhere in the code to stop execution and get a debugger console
gem 'pry-rails'
gem 'byebug'
# Access an IRB console on exception pages or by using <%= console %> in views
gem 'web-console', '~> 2.0.0.beta4'
# Spring speeds up development by keeping your application running in the background. Read more: https://github.com/rails/spring
gem 'spring'
end
app/assets/stylesheets/custom.css.scss
#import "bootstrap-sprockets";
#import "bootstrap";
views/layouts/application.html.erb
<!DOCTYPE html>
<html>
<head>
<title>THE BLOGGER</title>
<%= stylesheet_link_tag 'application', media: 'all',
'data-turbolinks-track' => true %>
<%= javascript_include_tag 'application', 'data-turbolinks-track' => true %>
<%= csrf_meta_tags %>
<!--[if lt IE 9]>
<script src="//cdnjs.cloudflare.com/ajax/libs/html5shiv/r29/html5.min.js">
</script>
<![endif]-->
</head>
<body>
<header class="navbar navbar-fixed-top navbar-inverse">
<div class="container">
<nav>
<ul class="nav navbar-nav pull-right"></ul>
</nav>
</div>
</header>
<div class="container">
<%= yield %>
</div>
</body>
</html>
You should not remove the application.css manifest file. You should, however, change it's name to application.css.scss. This way it can be preprocessed by SASS.
If you are including the imports for bootstrap in a separate file as you do in your example (custom.css.scss), you must ensure that this file are included in the application manifest. The require_tree directive that is included by default does this (you need to have the file located in the /stylesheets directory, like you do):
#application.css or application.css.scss
*= require_tree .
However, since you are using SCSS, I recommend the following approach:
#application.css.scss
#...
#all your files and directives
#...
#import "bootstrap-sprockets";
#import "bootstrap";
This way, it is not necessary to have a separate file like custom.css.scss