JW-Player and Rails 3.2 - ruby-on-rails

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.

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 JW Player to play video in rails?

I have a rails application which use Paperclip gem to upload the videos and paperclip-av-transcoder gem to convert the format and size of videos.
Currently, I use
video_tag vod.video(:sd), controls: true, type: "video/mp4", size: "400x400"
to display the videos, but It can only display one format.
Therefore, I want to use JW Player to display the videos. But I didn't find the user guide in the official website. Even I cannot find the download link.
So how to use the jwplayer in my app? What html code and javascript code I should write in my html file?
Note: #vod is the model of video, #vod.video is the attribute to store the video
Reference:
Gem jwplayer-rails
Customization Reference:
Add this line to your application's Gemfile:
gem 'jwplayer-rails'
First include assets on the page
<%= jwplayer_assets %>
Than place a div with JW Player
<%= jwplayer %>
You can pass options to jwplayer helper to customize it:
<%= jwplayer({file: vod.video(:sd), width: 500, height: 200}) %>
User JwPlayer without gem:
html:
<div id='myElement'>Loading the player ...</div>
jquery:
<script type='text/javascript'>
var playerInstance = jwplayer('myElement');
playerInstance.setup({
file: '/uploads/example.mp4',
image: '/uploads/example.jpg'
});
</script>
Link to setup start guide.

asset_path returns wrong path for folder

I have .swf files under vendor/assets/images/swf/. I need the asset path of that folder.
But this (.js.coffee.erb)
#= soundmanager2
$ ->
soundManager.setup
url: '<%= asset_path "swf/" %>'
is rendering this (.js):
(function() {
var $ = jQuery;
$(function() {
return soundManager.setup({
url: '/swf/'
});
});
}).call(this);
I am using rails 4.0.0.rc1. I am on development mode. The path /assets/swf/soundmanager2.swf returns 200, while /swf/soundmanager2.swf returns 404. The helper image_path returns /images/swf/, but /images/swf/soundmanager2.swf also returns 404.
It is not worth the trouble, because you would have to disable digest to get the name of the files right. So the solution is to fix the library. In the case of Sound Manager 2, I did this:
Some CoffeeScript that I require:
#= require soundmanager2
jQuery ->
soundManager.swfNames =
"/soundmanager2.swf": "<%= asset_path('swf/soundmanager2.swf') %>"
"/soundmanager2_debug.swf": "<%= asset_path('swf/soundmanager2_debug.swf') %>"
"/soundmanager2_flash9.swf": "<%= asset_path('swf/soundmanager2_flash9.swf') %>"
"/soundmanager2_flash9_debug.swf": "<%= asset_path('swf/soundmanager2_flash9_debug.swf') %>"
soundManager.setup
debugMode: <% if Rails.env.development? %>true<% else %>false<% end %>
url: '/'
In my copy of soundmanager2.js (V2.97a.20130512), inside the definition of normalizeMovieURL:
url = ... // After url is set
url = sm2.swfNames[url]; // Workaround
on rails 4 all the asset helpers (image_path, asset_path and the likes) appear to only return a config.assets.prefix-prefixed path if the asset you're accessing is actually resolvable by sprockets.
put simply: it must exist in you asset path on the disk after precompilation.
therefore, asset_path('swf/') will not work since it is a directory and not a file.
also, i experienced the following: rails < 4 (sprockets, rather) copied original images (and thus swf files) and created a digested version of that same file. because of this soundmanager was still able to find the non-digested swf files even though i have config.assets.digest = true.
with rails 4, these original images are not copied anymore because they changed some precompile internals which leads soundmanager to throw up if it wants to fallback to flash.
to properly fix this soundmanager needs to be patched, like michelpm proposes.
for soundmanager-rails i started working on a fix including a proper patch for soundmanager which you can find over on github.

What wysiwyg editor can I use for my rails 3.1 app with support of image uploader?

I tried this editor, but received many errors, maybe existing some editor, which I can easy install and update images.
My answer:
Now I use this editor, very easy to install.
Im using tinymce with the gem 'tiny_mce' and carrierwave for image upload.
My setup for tinymce is following:
$(function() {
tinyMCE.init({
mode: "textareas",
editor_deselector: "plain",
theme: "advanced",
plugins: "advimage,inlinepopups,save,autosave",
external_image_list_url: '#{image_list_admin_static_images_url}',
relative_urls: false,
theme_advanced_buttons1: "bold,italic,underline,strikethrough,|,justifyleft,justifycenter,justifyright,justifyfull,|,formatselect",
theme_advanced_buttons22: "",
theme_advanced_buttons3: "",
theme_advanced_toolbar_location : "top",
theme_advanced_blockformats: "p,h2,h3,h4"
})
}
The important part is image_list_admin_static_images_url in my routes i have:
resources :static_images do
get :image_list, :on => :collection
end
Method in StaticImagesController looks like:
def image_list
#image_list = "var tinyMCEImageList = #{StaticImage.image_list.to_json}"
render :js => #image_list
end
And in image_list method located in the model:
def self.image_list
all.map{ |im| [im.alt, im.image.url] }
end
This setup works perfectly for me, ofc you need to customize it for your own needs. Hope this will help you. TinyMCE is really nice and powerfull wysiwyg editor.
As chech suggested in the comments section, here is how you can adjust this solution for use with active_admin:
To use it inside active admin simply replace the route for this one:
match "admin/model_name/:id/js_image_list", :action => "js_image_list", :controller => "admin/model_name". Then create an action called js_image_list inside the active admin model file. Configuration for tinyMCE.init is: external_image_list_url : "js_image_list"
It seems like tinymce is definitely supported by rails 3.1. Here is the link
http://rubygems.org/gems/tinymce-rails
All you have to do is add the following to your Gemfile
gem 'tinymce-rails'
You have the following options to add to application.js depending on whether you want to use jquery or not
//= require tinymce-jquery
//= require tinymce
Personally I chose jquery so I added this line to the js.coffee file corresponding to my controller/view
tinyMCE.init
mode: 'textareas',
theme: 'advanced'
If you don't want to use jquery you can just add this script to your view
<script type="text/javascript">
tinyMCE.init({
mode: 'textareas',
theme: 'advanced'
});
</script>
I had problems with tinymce and Rails asset pipeline. I have not, also, found a way to start tinymce with increased font size. The default font size is very small.
If you are using twitter bootstrap one fantastic option is:
https://github.com/jhollingworth/bootstrap-wysihtml5
If you want something that works with HTML5 I would go with:
http://jejacks0n.github.com/mercury/
Awesome!

Ruby/Rails - Ways to stream audio (mp3/wav/etc)...Gem/Plugins vs HTML5?

I have a rails app that is coming along nicely...I would like to give the users the ability to upload and stream uploaded mp3s.
Currently I'm uploading to Amazon S3 through Paperclip with my site hosted on heroku.
I can upload the mp3s perfectly fine, so now I'm just looking for a way to support the playing of the actual files.
Are there any good gems/plugins that work with this issue that someone has used before?
Should I just go ahead and try to figure out how to do it with HTML5?
Anyone suggestions or opinions?
I would just use HTML5 and jquery, seems to be the most straightforward approach.
add gem 'jquery-rails', '>= 1.0.3' to your Gemfile and run 'bundle install'
Then add some markup in your views to give the divs and links for playing songs an id and class name. In this case the div/section id is "song" and the classname for the link is "play_song".
<h2>Listen to Song</h2>
<section id="song">
</section>
<td><%= link_to "HTML5 Audio", download_url_for(song.key), :class => "play_song" %></td>
Then in your js file:
$(document).ready(function() {
var audioSection = $('section#song');
$('a.play_song').click(function() {
var audio = $('<audio>', {
controls : 'controls'
});
var url = $(this).attr('href');
$('<source>').attr('src', url).appendTo(audio);
audioSection.html(audio);
return false; });
});

Resources