Cannot get styles to load with Rails 5 & vue2-dropzone - ruby-on-rails

I'm trying to get vue2-dropzone (version 3.0.3) to cooperate nicely with my Rails 5.1.4 app. I've added Dropzone to to my form and loaded the module but somehow I am not able to see the default styles. I don't think this is a problem with vue2-dropzone as much as with how webpacker loads the css.
My current setup:
application.js
import vue2Dropzone from 'vue2-dropzone'
import 'vue2-dropzone/dist/vue2Dropzone.css'
const myForm = new Vue({
el: '#multistep-form',
components: {
vueDropzone: vue2Dropzone
},
data: function () {
return {
dropzoneOptions: {
url: 'https://httpbin.org/post',
thumbnailWidth: 150,
maxFilesize: 5,
dictDefaultMessage: "<i class='fa fa-cloud-upload'></i> Drop files here to upload",
headers: { "My-Awesome-Header": "header value" }
}
}
}
and my _form.html.erb partial:
<vue-dropzone ref="myVueDropzone" id="dropzone" :options="dropzoneOptions">
</vue-dropzone>
I see that the Dropzone form is loaded. However, I cannot see the default style. I see the following in the console when I run :
Child extract-text-webpack-plugin node_modules/extract-text-webpack-plugin/dist node_modules/css-loader/index.js??ref--1-2!node_modules/postcss-loader/lib/index.js??ref--1-3!node_modules/vue2-dropzone/dist/vue2Dropzone.css:
[0] ./node_modules/css-loader?{"minimize":false,"sourceMap":true,"importLoaders":2}!./node_modules/postcss-loader/lib?{"sourceMap":true,"config":{"path":"/Users/myuser/Documents/apps/myapp/.postcssrc.yml"}}!./node_modules/vue2-dropzone/dist/vue2Dropzone.css 30.5 kB {0} [built]
I don't think it's an error since it says webpack: Compiled successfully. but I do think that webpack isn't loading vue2Dropzone.css for some reason. How should I configure webpacker to load that css file?
If I put the css file manually into my app/assets/stylesheets/ then it works without a problem.
Thanks in advance!

I think your CSS file should be loaded in CSS and not in js.
Here's how I'm doing it in my project.
Create application.css in packs folder and import into the Rails layout file, application.html.erb
<%= javascript_pack_tag 'application' %>
#import 'vue2-dropzone/dist/vue2Dropzone.css'
If you do this though, you will get an error because #import is a sass syntax. So you will need to do some extra webpack config.
You will find this post useful if you want to use css inside the application.js file.
https://medium.com/#mayorsan/rails-angular-webpacker-gem-like-a-pro-7cf40a588ab9

Related

How to call a javascript function inside a rails view?

I did just a upgrade from RAILS 5 to RAILS 6 and I see that all rails views are not able to call a javascript function as before in RAILS 5.
I have an external javascript file located under
app/javascript/packs/station.js
This is is embeded in in app/views/layouts/application.html.erb as
<%= javascript_pack_tag 'station' %>
This is the code how I call the javascrpt function from html.erb file :
<%= text_field_tag(:station_text_field, ... ,
onkeyup: "javascript: request_stations(); ") %>
When I try to call a function thats is part of the station.js then I get an error in the browser developmer view: ReferenceError: request_stations is not defined
But I can also see in the brwoser view, under Debugger :
Webpack / app/javascript / packs / station.js
and the javascript function I want to call.
So it seems that this script was loaded by the browser.
In contrast, when I just copy and paste these few lines that represent this javascript function direct into the template view file (...html.erb), something like :
<script>
function request_stations ()
{
alert("calling request_stations");
};
</script>
then - it works as expected !
By default, variables/functions defined inside JavaScript files that are packed by Webpacker will not be available globally.
This is a good thing, because it prevents global naming conflicts. Generally speaking, you don't want to reference javascript functions/variables from your view. You instead want to write JavaScript in a way that attaches functionality to DOM nodes using their id or other attributes.
Here is a basic example based on the code you provided:
# in your rails view
<%= text_field_tag(:station_text_field, ..., id: 'station-text-field') %>
// in your javascript
function request_stations() {
alert("calling request_stations");
};
const stationTextField = document.querySelector("#station-text-field");
stationTextField.addEventListener('keyup', (event) => {
request_stations();
});
Agree with mhunter's answer.
This post helped me get a grounding on this difference in Rails 6: https://blog.capsens.eu/how-to-write-javascript-in-rails-6-webpacker-yarn-and-sprockets-cdf990387463
What I don't see in your question is whether or not you did this in app/javascript/packs/application.js:
require("#rails/ujs").start()
require("turbolinks").start()
require("#rails/activestorage").start()
require("channels")
require("station")
The big difference in Rails 6 is that you have to deliberately:
require a JS file
deliberately export something from that file
deliberately import that something, in the file where you want to use it.
So if there is a function in station.js that you want to use, connect the steps above. Start with a simple function in station.js that fires upon DOMContentLoaded, and add a console.log("hey, station.js is alive and well"). If you don't see it, then something in those 3 steps is not right.
In pre-Rails6, you had a "garden" of JavaScript, just by virtue of being in the asset pipeline. In Rails 6, you have to be more deliberate.

How to use rails webpack loaded js in js erb template

I am using webpacker gem in rails 5.0 app, but I can't get the javascript to execute/be available in the js.erb I'm hitting on validation error. I'm sure that I'm violating some simple premise here, but can't find the answer and no compile or console errors are present. I do have the <%= javascript_pack_tag 'application' %> in my application.html.erb
Here is the setup:
app/javascript/packs/application.js:
import * as CustomerSession from 'customer_sessions';
console.log('Hello World from Webpacker');
app/javascript/customer_sessions/index.js:
export { univgwTabs } from './univgwTabs';
app/javascript/customer_sessions/univgwTabs:
export let univgwTabs = () => {
console.log('hi');
};
js erb template called on validation error of form:
$("#right_side_right_bottom_target").html("<%= j render partial: 'generic_object_new' %>");
CustomerSession.univgwTabs();
Global.resizeWindow();
If there is no issue with console.log(CustomerSession) in the location where you are importing it then the simplest fix I found was to just assign the imported variable as one of the global windows properties.
// in packs/application.js (or wherever your pack is)
// import
import * as CustomerSession from 'customer_sessions';
// assign
window.CustomerSession = CustomerSession
Assuming that there is no issues with webpacker, you should now be able to console.log(CustomerSession) in the console or your js.erb file.

JW-Player and Rails 3.2

I'm trying to use JW-Player in my application. Researching the issue a bit, there seems to be several abandoned efforts to produce a gem, and the latest is undocumented. So, here's how I'm going about it:
I downloaded the JW-Player version 6, unzipped and copied the files in my /app/assets/javascripts directory as follows:
app/assets/javascripts/jwplayer/jwplayer.js
app/assets/javascripts/jwplayer.html5.js
app/assets/javascripts/jwplayer.flash.swf
In my app/views/layouts/application.html.erb, I have the following:
<head>
<%= javascript_include_tag "/assets/javascripts/jwplayer/" %>
</head>
and in app/views/pages/about.html.erb, I have the following:
<%= jw_player("http://xxxxx/video.mp4",
:width => 200, :height => 110) %>
Here's what happens when I click on the About page link:
Showing xxxxxxxx/app/views/pages/about.html.erb where line #10 raised:
undefined method `jw_player' for #<#<Class:0x007fe77e37c018>:0x007fe780c1f678>
First time user of JW-Player.
When implementing JWPlayer 6.6, we stood before the choice of putting the jwplayer.flash.swf file into the public folder, to make the flash mode work, but it seemed very messy to have the files separated like that. What I did in the end to make it work both on development and production was:
Put all 3 files to vendor/assets/javascripts/jwplayer
Rename jwplayer.js to jwplayer.js.erb
Inside jwplayer.js.erb, update the flash file path config like this (the 1st line with the html5 file path config is just for reference)
j={type:"html5",src:e.base+"jwplayer.html5.js"},
b={type:"flash",src:"<%= asset_path('jwplayer/jwplayer.flash.swf') %>"};
(note that the "e.base+" before the path was removed for the flash file path - that's the trick that allowed working relative paths in the development environemtn)
In my understanding, the JWPlayer license allows modifications like this:
"Adaptations
Publisher shall be permitted to make Adaptations reasonably necessary for the purpose of exercising its rights under these Terms of Service, such as Adaptations to integrate the Products into Publisher’s websites or other properties. All Adaptations created by Publisher are strictly for its own Use and Publisher is prohibited from Distributing any Adaptation it creates. The Company reserves the right to prohibit the Use of any Adaptation in its sole discretion."
I have just finished working on a gem started by choix and improved by mattherick called jwplayer-rails that probably worked in older version of rails. It wasn't working with the assets pipeline but mattherick did a great job at fixing that up and I went on to update JWPlayer to the newest version.
You can see the repository here.
The following instructions are right out of the repo above.
To add this gem to your rails app just add this line to your application's Gemfile:
gem 'jwplayer-rails', :git => 'git://github.com/dutgriff/jwplayer-rails.git'
To use it first include assets on the page
<%= jwplayer_assets %>
Then place a div with JW Player
<%= jwplayer %>
You can pass options to jwplayer helper to customize it:
<%= jwplayer({width: 500, height: 200}) %>
More information for customization could be found here.
It works great for me so far but if you find an issue let me know on here or github.
I've found a solution to this.
The main issue you need to work-around is that jwplayer.js wants to fetch jwplayer.flash.swf and jwplayer.html5.js based on the path of jwplayer.js.
You can see that in Chrome Developer Toolbar for jwplayer.js (with pretty print):
(h.embed.config = function(b) {
var e = {fallback: !0,height: 270,primary: "html5",width: 480,base: b.base ? b.base : j.getScriptPath("jwplayer.js"),aspectratio: ""};
b = j.extend(e, h.defaults, b);
var e = {type: "html5",src: b.base + "jwplayer.html5.js"},
g = {type: "flash",src: b.base + "jwplayer.flash.swf"};
You can use that base property as an undocumented api to tell jwplayer where the jwplayer.flash.swf and jwplayer.html5.js can be found.
Example:
jwplayer("player-id").setup({
width: 640,
height: 480,
file: "www.w3schools.com/html/movie.mp4",
base: "http://cloudfront.net/assets/vendor/jwplayer/"
};
Then it will look for http://cloudfront.net/assets/vendor/jwplayer/jwplayer.flash.swf. Note: jwplayer has no notion of the asset pipeline fingerprint filenames, so make sure you sync both the file with md5 and without.
This worked for me:
Place jwplayer folder in public (Downloaded from longtail video)
Include it like an external script, without using asset pipeline (HAML).
%script{:src => '/jwplayer/jwplayer.js'}
In your video partial (ERB)
<script type="text/javascript">
jwplayer.key="Your key here";
$(document).ready(function(){
jwplayer("video").setup({
height: 360,
width: 640,
playlist: [
<% videos.each do |v| %>
{
image: "<%= v.poster %>",
sources: [
{ file: "<%= v.url %>" },
]
},
<% end %>
]
});
})
</script>
<video id="video">Video Loading... Ensure JavaScript is enabled...</video>
Did you restart the server after downloading the player and including it in your layouts. This could be one reason of failure.
Download jwplayer from http://www.longtailvideo.com/jw-player/download/
Put these files to the particular directory:-
app/assets/jwplayer/jwplayer.flash.swf
vendor/assets/javascripts/jwplayer.js
vendor/assets/javascripts/jwplayer.html5.js
Then add these line in application.js
//= require jwplayer
//= require jwplayer.html5
On the page where you are playing video, add these lines
<script type="text/javascript">jwplayer.key="YOUR_JWPLAYER_KEY";</script>
<div id="video">Loading the player ...</div>
<script type="text/javascript">
jwplayer("video").setup({
flashplayer: "<%=asset_path('jwplayer.flash.swf')%>",
file: "<%= file_path %>",
height: 360,
width: 640,
analytics: {
enabled: false,
cookies: false
}
});
http://account.longtailvideo.com/#/home from where you can get your free self hosted key in signing up from Get Your License Key portion.
I also chose JWplayer.
Here are my steps.
I'm using https://github.com/choix/jwplayer-rails gem.
Added
gem 'jwplayer-rails', '1.0.1'
to my Gemfile.
Did all things from above page; in a show.html.slim view file included these lines:
= jwplayer_assets
br
br
= jwplayer({file:#lesson.media_file})
lesson.media_file attribute contains file location. For a video file project/public/videos/videoclip.webm, media_file contains string "/videos/videoclip.webm".
Hope this will be useful.

jasmine not loading my custom js file

I am unable to get jasmine to load my custom javascript file, even though it works perfectly in the browser. I've reduced the javascript to the minimum to avoid any possibility of errors and I still get a failing test on the simplest thing.
Custom ARB.js file:
$(document).ready(function() {
alert('typeof ARB: ' + typeof ARB);
});
ARB = {};
ARB.VERSION = "V1.01.00 2012-08-24";
jasmine configuration file snippet (I'm on Rails 3.0.9):
src_files:
- "public/javascripts/**/*.js"
- "public/javascripts/ARB.js"
This test:
it('should define the custom javascript functions', function() {
expect(typeof ARB).toEqual('object');
});
fails with:
Expected 'undefined' to equal 'object'.
jQuery gets loaded and so does my application.js file. When running jasmine, I get no alert message, but I do when I run my app.
What am I missing?
UPDATE: If I remove the $(document).ready function, jasmine passes all the tests - what's that all about?
shioyama gave me the pointer that I needed to figure this out: my custom ARB.js file was getting loaded before the jquery files so it didn't have access to the $(document).ready function. What I had to do was explicitly spell out the order in which my javascript files were to be loaded. Here's what I put in my jasmine config file at /spec/javascripts/support/jasmine.yml:
src_files:
- "public/javascripts/**/jquery.js"
- "public/javascripts/**/jq*.js"
- "public/javascripts/**/application.js"
- "app/assets/javascripts/**/*.js"
- "public/javascripts/ARB.js"
I first force the main jquery.js file to load, then all the other jquery files, then application.js, then any other javascript files that are located in the assets directory, and finally my custom javascript file.
This works for me because I'm still on Rails 3.0.9 and starting the migration to 3.1+ and the asset pipeline.

Rails 3 - How to use stylesheet's compiled name inside javascript file?

I have javascript file in rails app, where i pull in the stylesheet like this -
loadAssets: function(){
var stylesheet = document.createElement('link');
stylesheet.href = "<%= asset_path('lib/myStyles.css') %>";
stylesheet.rel = 'stylesheet';
stylesheet.type = 'text/css';
document.getElementsByTagName('head')[0].appendChild(stylesheet);
}
But asset_path helper used here, just gives plain myStyles.css name, where it should have been compiled name of that css file.
Because of this, i can't expire cache and get new myStyles.css file.
So, my question is, how can i get compiled name of this myStles.css file in my javascript file. Above code containing javascript file also gets compiled.
<%= asset_path('lib/myStyles.css'), :digest => true) %>

Resources