Adding OpenLayers to rails project - javascript

I have been reading some posts related with this issue, but i couldn't get this working.
I tried to use the 'openlayers-rails' gem and also i tried adding the OpenLayers folder to /vendor/assets/javascript/ (with the require //= require OpenLayers/OpenLayers into the /assets/javascript/application.js file). I both scenarios i get "Uncaught ReferenceError: OpenLayers is not defined" as a browser inspector error.
Any help is appreciated!
Thanks

The README for the openlayers-rails gem says that you should include the JS this way:
//= require openlayers-rails
Not with //= require OpenLayers/OpenLayers

Related

Multiple Uncaught Errors Using the react-rails Gem

To preface my question, I am following this guide.
When trying to build a CRUD interface using Rails and React, I receive this error when trying to create a new item:
addComponentAsRefTo(...): Only a ReactOwner can have refs. You might be adding a ref to a component that was not created inside a component's render method, or you have multiple copies of React loaded.
I wasn't improperly adding a ref attribute to any JSX not inside of a render method, so I must have multiple copies of React within my asset pipeline.
Research yielded the following potential results:
Introducing webpack or Searchkit, suggested in this SO answer, seemed to be clunky workarounds for my simple CRUD interface.
This unselected SO answer suggested removing the //= require react line from ./app/assets/javascripts/application.js. This proved to be unsuccessful.
Issue #671, from the official GitHub react-rails repo. here, outlines the first part of my issue perfectly. I followed this potential solution, which suggests removing the //= require react-server line of the ./app/assets/javascripts/server_rendering.js file. This lead to a new error, outlined below:
Uncaught ReferenceError: $ is not defined
Which I assume means that react_server not only contains a second copy of React, but also loads something vital for my AJAX calls.
For reference, here are the contents of ./app/assets/javascripts/application.js:
// This is a manifest file that'll be compiled into application.js, which will include all the files
...
// about supported directives.
//
//= require rails-ujs
//= require react
//= require components
//= require turbolinks
//= require_tree .
and ./app/assets/javascripts/server_rendering.js:
//= require react_ujs
//= require react-server
//= require ./components
...
Where a set of ellipses, or ..., are used to shorten known comment sections.
Ruby version: 2.3.3p222 (2016-11-21 revision 56859)
Rails version: 5.1.1
react-rails version: 2.2.0
The third potential answer, or removing the //= require react-server from ./app/assets/javascripts/server_rendering.js, was a step in the right direction.
Removing this line doesn't yield a new issue, it just reveals another error you had the entire time. react_server doesn't define the $ variable for AJAX calls, the jQuery gem does.
Found here. I am confident in this solution because the error:
Uncaught ReferenceError: $ is not defined
is a jQuery issue, as the AJAX calls you are probably making take a form referenced in their official doc. here.
Therefore, after running gem install jquery-rails in your shell, your ./app/assets/javascripts/application.js should look like this:
...
//= require rails-ujs
//= require jquery
//= require react
//= require components
//= require turbolinks
//= require_tree .
Your ./app/assets/javascripts/server_rendering.js file should look like this:
//= require react_ujs
// require react-server
//= require ./components
...
Note that require react-server is commented out.
And make sure to follow the solution found in this SO answer regarding the .\app\views\layouts\application.html.erb file.

Rails 4 jQuery conflicts with javascript

Im trying to make an app in Rails 4.
I'm struggling. I'm trying to incorporate a bootstrap theme and I'm getting issues with the vendor javascripts and the rest of the code.
I think the problem might have something to do with having jQuery in my application.js and then having vendor .js files which start with a '$' sign:
$.circleProgress = {
I've just read this: https://learn.jquery.com/using-jquery-core/avoid-conflicts-other-libraries/
My problem is though that I don't know how to make the changes that make the code safe.
Do I need to do a search for every '$' in the vendor files or otherwise how do i put a safe wrapper on jQuery - especially where it is incorporated through a gem.
Has anyone encountered these problems and figured out a solution? I'd love some help.
Application.js
//= require jquery
//= require bootstrap-sprockets
//= require jquery_ujs
//= require html.sortable
//= require disqus_rails
//= require moment
//= require bootstrap-datetimepicker
//= require pickers
//= require main
//= require hammer.min
//= require jquery.animate-enhanced.min
//= require jquery.countTo
//= require jquery.easing.1.3
//= require jquery.fitvids
//= require jquery.magnific-popup.min
//= require jquery.parallax-1.1.3
//= require jquery.properload
//= require jquery.shuffle.modernizr.min
//= require jquery.sudoSlider.min
//= require jquery.superslides.min
//= require masonry.pkgd.min
//= require rotaterator
//= require smoothscrolljs
//= require waypoints.min
//= require wow.min
//= require gmaps/google
//= require chosen-jquery
//= require cocoon
//= require imagesloaded.pkgd.min
//= require isotope.pkgd.min
//= require jquery.counterup.min
//= require jquery.pjax
//= require custom.js
//= require slider
//= require underscore
//= require dependent-fields
//= require_tree .
//= require bootstrap-slider
$(document).ready(function() {
DependentFields.bind()
});
Related problem: Rails 4 - incorporating vendor assets
Observation
I've noticed that the console log of errors shows problems with .js files in my app/assets/javascripts folder.
They are the only other files in that folder (aside from application.js). My application.js has 'require_tree' so they will be compiled. But something I think might be conflicting in those files with (perhaps) the inclusion of jQuery in the application.js?
The log shows:
Uncaught SyntaxError: Identifier 'findGoodContent' has already been declared
circle-progress.self-f67ec54c54a06da27d11cda862036a058792eadc8ef982df2e7c0a1682536c31.js:9 Uncaught TypeError: Cannot set property 'circleProgress' of undefined
conversations.self-832ece2867c1701a5202459ab73ecd6432da2a6c833d8822d37025845a0aefcc.js:10 Uncaught TypeError: $ is not a function
organisations.self-6547f734e3a69b76176dfe5bb194e428c0bc560ad3fb69811dce9c7f8ccb9f4d.js:2 Uncaught TypeError: $ is not a function
http://localhost:3000/assets/%3C%=%20asset_path('random.jpg')%20%%3E Failed to load resource: the server responded with a status of 400 (Bad Request)
http://localhost:3000/profiles/assets/images/grayscale.svg#greyscale Failed to load resource: the server responded with a status of 404 (Not Found)
http://localhost:3000/assets/vendor/assets/fonts/Simple-Line-Icons.woff Failed to load resource: the server responded with a status of 404 (Not Found)
http://localhost:3000/profiles/assets/custom/images/preloader.gif Failed to load resource: the server responded with a status of 404 (Not Found)
chrome-extension://mkjojgglmmcghgaiknnpgjgldgaocjfd/content/contentScripts/kwift.CHROME.min.js:1384 Uncaught SyntaxError: Identifier 'findGoodContent' has already been declared
http://localhost:3000/assets/flaticon.woff Failed to load resource: the server responded with a status of 404 (Not Found)
http://localhost:3000/assets/vendor/assets/fonts/Simple-Line-Icons.ttf Failed to load resource: the server responded with a status of 404 (Not Found)
http://localhost:3000/assets/flaticon.ttf Failed to load resource: the server responded with a status of 404 (Not Found)
main.self-5888479bd3eb03114ce5776dd32cfadf84f1d3a4335043513f8b1606d3ab5f4a.js:316 Uncaught TypeError: dp(...).multipleFilterMasonry is not a function
Each of the js folders that are identified as errors are saved as .js files in app/assets/javascripts.
Do I perhaps need to use a different file name (.js.erb / js.coffee)? to make this work. Alternatively, do I need to put script tags around the content of those files?
For example, the first file opens with:
$.circleProgress = {
// Default options (you may override them)
defaults: {
/**
* This is the only required option. It should be from 0.0 to 1.0
* #type {float}
*/
value: 0,
UPDATE
I think some part of my problem is to do with the files saved in app/assets/javascripts with ".js" extensions. Each of them shows in the console errors list as:
kwift.CHROME.min.js:1271Uncaught SyntaxError: Identifier 'findGoodContent' has already been declared
circle-progress.self-f67ec54….js?body=1:9 Uncaught TypeError: Cannot set property 'circleProgress' of undefined(anonymous function) # circle-progress.self-f67ec54….js?body=1:9
conversations.self-832ece2….js?body=1:10 Uncaught TypeError: $ is not a function(anonymous function) # conversations.self-832ece2….js?body=1:10
organisations.self-6547f73….js?body=1:2 Uncaught TypeError: $ is not a function(anonymous function) # organisations.self-6547f73….js?body=1:2(anonymous function) # organisations.self-6547f73….js?body=1:6
projects.self-9c019ba….js?body=1:1 Uncaught TypeError: $ is not a function(anonymous function) # projects.self-9c019ba….js?body=1:1
main.self-5888479….js?body=1:316 Uncaught TypeError: dp(...).multipleFilterMasonry is not a functionwindow.onload # main.self-5888479….js?body=1:316
kwift.CHROME.min.js:1271 Uncaught SyntaxError: Identifier 'findGoodContent' has already been declared
It sounds like you have a lot of cleanup to do. Is this your first Rails app? If so I'm curious why you have so many JS files already. I would cut back your list to just a few, fix the problems that remain, and slowly start adding things and fixing problems as you go. That would be my general strategy. For each bug, go slow and double-check that you really understand the cause, before you slash here and there hoping for a fix.
Here are some tips for specific bugs I see:
This line will include all the .js files in app/assets/javascripts:
//= require_tree .
The problem is that you're already including them one-by-one above. So they are getting included twice. That's why you're getting warnings like 'findGoodContent' has already been declared. I know it is kind of nice to use require_tree (though I don't love it), so if you want to keep that, consider moving all the 3rd-party JS files out of app/assets/javascripts and into vendor/assets/javascripts. You can still require them in your application.js, but they won't get repeated by require_tree.
The 404 errors for things like grayscale.svg and flaticon.woff and other image/font assets are because you don't have those files in app/assets (or vendor/assets). Or if you do, you should make sure your JS/CSS files and view files refer to them with <%= asset_path "grayscale.svg" %> so that when Rails mangles their path you are still loading them from the right place. Read about image_url and friends and make sure you understand how they work. By default, the Asset Pipeline serves unmangled names in development and mangled names in production, so things might work right up until you push it all live!
Also, if you include <%= foo %> tags in a CSS file or JS file, then you need to add an .erb extension to that file, so that Rails knows to process those tags. That's why you're getting a 404 error trying to load this:
http://localhost:3000/assets/%3C%=%20asset_path('random.jpg')%20%%3E
In one of your files, probably a CSS file, you're doing something like this:
background-image: url("<%= asset_path('random.jpg') %>");
But the file needs an .erb extension: blah.css.erb or blah.scss.erb or whatever.
Errors like $ is not a function mean that those files depend on jQuery, but the jQuery $ object is not defined. If you are using noConflict, as someone suggested in the comments, you should stop, because you do want $ to be the jQuery object.
Good luck! If you are feeling overwhelmed, I would really start with cutting out as many of the JS require lines as possible, and tackle the bugs one at a time.
Also, I would re-order the require lines so that dependencies are at the top (e.g. jquery), and things that rely on them are lower.
Oh one more thing, not really a bug: I would avoid putting already-minified files (like hammer.min.js) into your repository. The Asset Pipeline knows how to minify. So check in the unminified version, so that if you have to read the source code, you can.
I put this post out as a job on upwork.
The solution is complex, but in case it helps others to understand what's gone wrong:
some gems require jQuery features. That can clash with the general inclusion of jQuery in application.js - I had some specific code written to manage specific conflicts.
in application.js, you need to list all the requirements in order, so that dependencies are below the js file that depends on them. Its difficult to know which file depends on what. I never would have figured this out alone
my rake assets:precompile call puts compiled assets in the public folder. I overrode this because it was causing conflicts with other calls (especially when files are updated).
There is no real help in this answer for anyone trying to learn. I didn't exactly learn how to solve these problems myself, but I did find an expert on upwork, who was able to help so that I could move on.
I'm afraid this is one of those messy problems that the blog tutorials don't help with.
Not sure why no one has posted this but $.something in jQuery is just shorthand for jQuery.something.
The ability to disable this is baked into jQuery
https://api.jquery.com/jquery.noconflict/
Here is an example from their documents
jQuery.noConflict();
// Do something with jQuery
jQuery( "div p" ).hide();
// Do something with another library's $()
$( "content" ).style.display = "none";
Essentially it'll be a lot easier to just use "jQuery" vs "$" in your hand rolled code than change the inherited library. That being said you should submit a issue to the offending library to fix this functionality, similar to how jQuery does it, as jQuery is pretty popular.
Good luck!

angular-rails-templates Failed to load template

I'm trying to get Angular to load a template:
var app = angular.module("myApp", ['templates'])
and my html:
<div ng-app="myApp">
<div ng-include="'blah.html'"></div>
</div>
But all I get is a 404 Failed to load resource because, Rails tells me, No route matches [GET] "/blah.html". I understand that this is because of the asset pipeline in Rails. blah.html is in /app/assets/javascripts/templates/blah.html and I am using the angular-rails-templates gem to try to solve the problem. So my application.js has:
//= require angular-rails-templates
//= require_tree ./templates
But I'm not having any luck.
The html generated suggests that angular-rails-templates is loading (it has a script /assets/angular-rails-templates....js) but rails is failing to find blah.html
Versions:
rails 4.2.1
angular-rails-templates 0.1.4
angularjs 1.3.15
This turned out to be a sprockets incompatibility (see here and here)
The short version is:
Add gem 'sprockets', '2.12.3' to your Gemfile
Run bundle update sprockets
[Update]
I'm no expert on this stuff but it does seem that a number of people smarter than I are suggesting using /public/templates. You may want to bear this in mind.
I had a similar issue - In my haste, I neglected to fully read the directions, and missed step 3.
Adding a Dependency in the Angular Application Module solved it for me, and the templates are served through the asset pipeline...
//= require angular-rails-templates
//= require_tree .
angular.module('d-angular', ['templates'])
I put my angular template files under public/templates which is accessible via <site root>/templates without any additional configuration.
After struggling for an hour to get this, I realized that I had a JavaScript file sharing the same name.
For example, these files will cause conflict:
component.js
component.html.haml
So I made sure to rename the JavaScript file to something like:
component-directive.js
component.html.haml
I've been struggling on the same problem today, and I think I have found a solution for this problem.
try
<div ng-include="'assets/blah.html'"></div>
OR
<div ng-include="'assets/templates/blah.html'"></div>
instead of
<div ng-include="'blah.html'"></div>
This solved the problem for me.

Javascript plugins are not loading

I have cloned one rails(3.2.13) project from git repository. CSS styles are working fine. But whole javascript plugins are not loading.
Eg: Bootstrap's dropdown(nav-list) list is not showing, ajax request is not working etc.
I have checked it by precompiling the assets but still it is not working. I have checked the same project with others, it is working fine for them.
Please help me to solve this issue.
In application.js,
//= require jquery
//= require jquery_ujs
//= require twitter/bootstrap
//= require bootstrap-datepicker
//= require_tree .
In jquery console, i am getting below errors,
Uncaught SyntaxError: Unexpected token ILLEGAL
Uncaught ReferenceError: $ is not defined
Uncaught ReferenceError: jQuery is not defined
Add the below line to development.rb,
config.assets.debug = true
Here no need to precompile the assets.

Rails can't include AngularJS

I'm following this tutorial and although adding it to the Gem file and bundle installing it works fine. The moment I try to include it into application.js, the file, I get the following error while loading it:
throw Error("Sprockets::FileNotFound: couldn't find file 'angular'\n (in /my/path/to/rails/app/assets/javascripts/application.js:13)")
application.js file looks like so (starting with line 13):
//= require angular
//= require jquery
//= require jquery_ujs
//= require jquery.ui.autocomplete
//= require bootstrap
//= require pusher.min.js
//= require pusher_setup
//= require_directory .
Therefore, my question is how can I successfully include AngularJS into my Rails project?
I'm currently using Rails 3.2.2, and Ruby 1.9.3.
I had face same problem. I resolved it by following way.
1) In my case, //= require_tree . was missing in application.js file.. so i have added it.
2) Restarted Apache Server (If webrick, then restart it)
After adding a gem you always have to restart the web server.
From looking at the gem's source code, it has the angular javascripts in vendor/assets/javascripts, which means they will be available by just doing //= require angular. If they don't load, it's probably because the server needs to be restarted and you need to bundle install.
As for the require_tree ., I strongly advise against that, because it means you will lose control over the order in which things get loaded.
For example angular itself is packaged with it's own version of jQuery (jQuery-lite), but if there is already jQuery present when it is loaded, it will use the global version.
Which means doing
//= reqiure angular
//= require jquery
will do something different, than
//= require jquery
//= require angular
There are many other cases when load order can matter, for example if you have Backbone.js and Underscore, you will want to load Underscore before Backbone, etc.
As a general practice I would always recommend just using require, unless you're loading your own code where order doesn't matter, for example //= require_tree ./controllers for your own directory of controllers. In that case I'd say require_tree is perfectly ok.
in your gemfile if you are using like this :
group :assets do
gem 'angularjs-rails'
end
then remove that group :assets thing, It should be simple without block:
ex:
gem 'angularjs-rails'
It will definitely work
In case anyone had a same issue and the offered solution wouldn't work.
I have added //= require angular in the asset
group :assets do
//= require angular
end
However still I was getting the same error. After a bit of search I found out that for some reason it needs to be added outside of the assets group. All good now. Not sure if this is a best way though however I am not getting this error anymore.

Categories