?
Application.js is not evaluated in the context of any session variables or methods. The simplest way to access username from javascript would be to set a cookie in a before_action on application controller:
class ApplicationController < ActionController::Base
before_action :set_user
private
def set_user
cookies[:username] = current_user.name || 'guest'
end
end
Then from any js in app/assets you can access the cookie:
alert(document.cookie);
A more verbose but arguably cleaner method would be to create a route that accesses the current user and returns the username e.g.
routes.rb
get 'current_user' => "users#current_user"
users_controller.rb
def current_user
render json: {name: current_user.name}
end
application.js
$.get('/current_user', function(result){
alert(result.name);
});