load javascripts from asset pipeline in rails - ruby-on-rails

In a rails project, I want just use controller and model of rails application. For this purpose, I use angularjs. I put my angularjs file in assets/angular directory and I route url and set templates from app.js in angular. Know I deactive rails view by below code in application_controller.rb:
class ApplicationController < ActionController::Base
protect_from_forgery with: :exception
def index
render :layout => 'application', :nothing => true
end
end
config/routes.rb:
root to: 'application#index'
Know, when I run the server and project run on localhost:3000, my scripts don't load and <head> of html file is empty.
<html>
<head>
</head>
<body>
<pre style="word-wrap: break-word; white-space: pre-wrap;">
</pre>
</body>
</html>
This problem is about asset pipeline, and js don't load. How can I fixed this problem?
I have this code for angular:
asset/javascripts/angular/app.js.erb:
'use strict';
angular.module('app', ['ngResource'])
.config(['$routeProvider', function($routeProvider, $locationProvider) {
$routeProvider
.when('/', {controller: 'ForumIndexController', templateUrl: '<%= asset_path('templates/index.html') %>'})
.otherwise({redirectTo: '/'});
}
]);
view/layout/application.html.erb:
<!DOCTYPE html>
<html lang="en" ng-app="app">
<head>
<title>SimpleForum</title>
<%= stylesheet_link_tag "application", :media => "all" %>
<%= javascript_include_tag "application" %>
<%= csrf_meta_tags %>
</head>
<body>
<div class="container">
<div ng-view></div>
</div>
</body>
</html>
assets/javascripts/application.js:
//= require jquery
//= require jquery_ujs
//= require angular.min
//= require angular-resource.min
//= require ../angular/app
//= require_tree ../angular
How can I set rails application to load scripts?
Any Idea about fixed this problem?

I don't think you need the ../ infront of the angular folder, since it is at the same level as the manifest.
//= require angular/app
//= require_tree angular
Should be fine.

Related

Assets are reloaded between pages with Turbolinks 5 and Rails 5

In my production environment, I noticed Turbolinks was not caching assets between pages. When I come on the first page of my application, my javascript bundle gets loaded, so as my CSS. When I then get to another page with a link, I can see in the chrome devtools, network tab, that they are reloaded (HTTP code 200).
application.html.erb
<html>
<head>
<title>My title</title>
<meta name="description" content="My description">
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta name="robots" content="index, follow">
<meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
<%= javascript_include_tag 'application', 'data-turbolinks-track': 'reload' %>
<%= stylesheet_link_tag 'application', media: 'all', 'data-turbolinks-track': 'reload' %>
<link rel="stylesheet" type="text/css" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
<%= csrf_meta_tags %>
<%= action_cable_meta_tag %>
</head>
<body class="<%= body_user_class %> <%= controller.controller_name %>">
// Stuff
</body>
</html>
application.js
//= require turbolinks
//= require jquery
//= require jquery.slick
//= require jquery-ui/sortable
//= require rails-ujs
//= require_tree ./components
The fingerprint of the assets remains the same between the first and the second page, so I don't think the issue comes from there.
I can understand why my bootstrap asset is reloaded, as it is referenced as a classical resource without using rails. But why are my application's js and css reloaded?
In your application JavaScript bundle, you have the following:
document.addEventListener("turbolinks:before-visit", function(e) {
e.preventDefault(),
window.location = e.data.url
})
This cancels the default Turbolinks behaviour. If you remove this event listener, it should work as expected.

Angularjs $http.get( file.json ) resulting in No Route matches error (Cloud9 IDE)

I'm trying to render data from a JSON file via $http.get().
But when i run the app, the JSON data isn't rendered, and the developer console shows an error:
ERROR:
Failed to load. Resource. The server responded with a status of 404 (Not found).
Routing Error
No route matches [GET] "/phones.json"
THOUGHTS:
I've read that $http.get() follows a relative path to the the given URL, so if phones.json is in the same folder as index.html.erb, i can't figure out why its not loading.
I'm wondering if i need to add something to routes.rb.
controllers.js
var phonecatApp = angular.module('phonecatApp', []);
phonecatApp.controller('PhoneListCtrl', ['$scope', '$http',
function ($scope, $http) {
$http.get('phones.json').success(function(data) {
$scope.phones = data;
});
$scope.orderProp = 'age';
}]);
routes.rb
Rails.application.routes.draw do
resources :home
root 'home#index'
end
application.html
<!DOCTYPE html>
<html lang="en" ng-app="phonecatApp">
<head>
<meta charset="utf-8">
<title ng-bind-template="Phone Library: {{query}}">Phone Library</title>
<%= stylesheet_link_tag 'application', media: 'all', 'data-turbolinks-track' => true %>
<%= javascript_include_tag 'application', 'data-turbolinks-track' => true %>
<%= csrf_meta_tags %>
</head>
<body ng-controller="PhoneListCtrl">
<%= yield %>
</body>
</html>
index.html.erb
<div class="container-fluid">
<div class="row">
<div class="col-md-2"></div>
<div class="col-md-10">
<ul class="phones">
<li ng-repeat="phone in phones | filter:query | orderBy:orderProp">
{{ phone.name }}
<p>{{phone.snippet}}</p>
</li>
</ul>
</div>
</div>
</div>
application.js
//= require angular
//= require angular-route
//= require angular-resource
//= require angular-ui-bootstrap
//= require turbolinks
//= require_tree .
gems added:
gem 'angularjs-rails'
gem 'angular-ui-bootstrap-rails'
gem 'responders', '~> 2.0'
file tree
note:
This is part of an Angularjs tutorial called PhoneCat, chapter5 (url:https://docs.angularjs.org/tutorial/step_05). Though i made a few detours earlier on to make it work, so unable to follow it exactly at this point.
I'm not an expert in Rails or Angularjs so any advice would be highly appreciated :)

AngularJS with Rails asset pipeline

I cannot get Angular to work with Rails asset pipeline. I have:
application.js
//= require angular
angular.module('myApp', [])
.config([function() {
console.log('In config.');
}]);
application.html.erb
<!DOCTYPE html>
<html>
<head>
<%= javascript_include_tag 'application' %>
</head>
<body ng-app="myApp"></body>
</html>
When I load the page I do not see the expected "In config" in the console. Where are no errors prompted, the source is loaded correctly. After refreshing the page two times, on the third load the console message does appear eventually.
If I replace <%= javascript_include_tag 'application' %> with simply <script src="/assets/application.js"></script>, the application does work as expected.
What am I missing here?

Rails 4: Google Maps not displaying

I'm trying to display a simple Google Map on my Rails 4 app.
I chose to include the code statically for now until I get it to work.
In my _head.html.erb partial, I have:
<head>
<title><%= content_for?(:title) ? yield(:title) : t('website.name') %></title>
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<%= stylesheet_link_tag "application", media: "all", "data-turbolinks-track" => true %>
<%= javascript_include_tag "application", "data-turbolinks-track" => true %>
<%= yield(:google_maps_api) if content_for?(:google_maps_api) %>
<%= csrf_meta_tags %>
</head>
Then in another view, I have a partial called _google_map.html.erb that does the following:
<% content_for(:google_maps_api) do %>
<%= javascript_include_tag "https://maps.googleapis.com/maps/api/js?key=xyz&sensor=false" %>
<script type="text/javascript">
function initialize() {
var mapOptions = {
center: new google.maps.LatLng(-34.397, 150.644),
zoom: 8
};
var map = new google.maps.Map(document.getElementById("map-canvas"), mapOptions);
}
google.maps.event.addDomListener(window, 'load', initialize);
</script>
<% end %>
<div id="map-canvas" style="width: 100%; height: 100%"></div>
When I look at the source, the js and div are getting properly output to the page.
However, no map is displayed. Please note that I do have the following in my application.js file
//= require jquery
//= require jquery.turbolinks
//= require jquery_ujs
//= require jquery.ui.datepicker
//= require twitter/bootstrap
//= require turbolinks
//= require_tree .
Any idea why the map is not being displayed?
Thanks!
If the div is getting filled it but just isn't visible you may want to check the height. For the height: 100% to work it needs to be in a container that has a specific height. To see if the height is the problem, try something like:
<div id="map-canvas" style="width: 400px; height: 400px"></div>

Dojo + Rails 3.2.8 + CoffeeScript

I'm trying to use Dojo Toolkit 1.8 instead JQuery in a Rails 3.2.8 web application, mainly due of the lack of a complete and visually uniform widget based on JQuery. Followed these steps:
Unzip dojo, dijit and dojox directories into app/assets/javascripts
Changed in application.js //= require_tree . to //= require_directory .
Edited application layout (Not unobtrusive yet... just to effect of testing)
views/layouts/application.html.erb
<!DOCTYPE html>
<html>
<head>
<title>Dojo</title>
<%= stylesheet_link_tag 'application' %>
<%= javascript_include_tag 'application' %>
<%= stylesheet_link_tag '/assets/dijit/themes/claro/claro.css' %>
<%= javascript_include_tag "dojo/dojo", :'data-dojo-config' => 'async: true' %>
<%= csrf_meta_tags %>
</head>
<body class='claro'>
<%= yield %>
<script>
require(["dojo/parser", "dojo/ready"], function(parser, ready) {
ready(function() {
parser.parse();
});
});
</script>
</body>
</html>
Created a controller named home and a template to the index action
views/home/index.html.erb
<input type="text" required="true" name="bday" id="bday" data-dojo-type="dijit/form/DateTextBox" value=<%= localize(Date.today - 21.days) %> />
<button id="button1" type="button" data-dojo-type="dijit/form/Button">Button 1</button>
Ok, Dijit works nice! But when I try to put some dojo code within a CoffeeScript file (assets/javascripts/home.js.coffee), a "ReferenceError: require is not defined" error message is raised on Firebug console. Sample code:
require ["dojo/domReady!"], () ->
alert('ok')
If I put a //= require dojo/dojo before the code above, it runs, but all dojo modules are loaded (not just domReady) and a "Error: defineAlreadyDefined" is raised on Firebug.
Is there any way to call the require function without having to reload the entire dojo.js or even access a dojo global variable?
Thanks
It was a slip of mine, I swapped the javascripts inclusion order. The correct is:
<%= stylesheet_link_tag '/assets/dijit/themes/claro/claro.css' %>
<%= javascript_include_tag "dojo/dojo", :'data-dojo-config' => 'async: true' %>
<%= stylesheet_link_tag 'application' %>
<%= javascript_include_tag 'application' %>
Dojo wasn't loaded yet when I was trying to require modules within the coffeescript file.
Thank you for your attention.

Resources