How do I conditionally assign ruby variables to javascript variables?
        Posted  
        
            by Tony
        on Stack Overflow
        
        See other posts from Stack Overflow
        
            or by Tony
        
        
        
        Published on 2010-06-13T16:19:03Z
        Indexed on 
            2010/06/13
            16:22 UTC
        
        
        Read the original article
        Hit count: 242
        
JavaScript
|ruby
I have a website where I need a javascript version of the "current user" object along with the ruby version. I have been assigning these variables doing something like this...
Application Controller:
def get_user
    begin
      @current_user = User.find(session[:user_id]) if session[:user_id]
      @current_user_json = @current_user.to_json
    rescue
      session.delete(:user_id)
      @current_user = nil
      @current_user_json = {}
    end
  end
Web Page:
var current_user = null;
current_user_json = '<%= @current_user_json %>';
if(current_user_json != ''){
        current_user = current_user_json.user;
}
Even when there is a current user, I get the current user is undefined.  Probably because I am putting the current_user_json assignment around single quotes.  However, if I don't put it around single quotes, I'll always get a javascript error when no user is logged in because the syntax is invalid - 
current_user_json = ;
I think I am just looking at this completely wrong and there must be a better way. Given that this is probably a common thing to do, I wanted to get other people's opinion on how to create an object in javascript that is a duplicate of the ruby object.
© Stack Overflow or respective owner