2010-06-13 40 views
0

我有一个网站,我需要一个JavaScript版本的“当前用户”对象以及ruby版本。我一直在分配这些变量做这样的事情...我如何有条件地将ruby变量赋值给javascript变量?

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; 
} 

即使有当前用户,我得到的当前用户是未定义的。可能是因为我将current_user_json分配在单引号附近。但是,如果我不把它周围的单引号,我总是在没有用户登录一个JavaScript错误,因为语法无效 -

current_user_json = ; 

我想我只是看着这个完全错误并且必须有更好的方法。鉴于这可能是一件常见的事情,我想获得其他人关于如何在JavaScript中创建一个与Ruby对象相同的对象的意见。

回答

4

JSON是有效的Javascript。考虑取消引号,只是直接将其输出:

current_user_json = <%= @current_user.nil? ? '' : @current_user_json %>; 

更重要的是,有你的控制器做所有的工作而不是把逻辑视图:

@current_user_json = @current_user.nil? ? '{user: null}' : @current_user.to_json 
# ... 
current_user_json = <%= @current_user_json %>; 

(编辑:下面股份有限公司尖尖的建议。 )

+2

除“无”情况下,JSON不能只是空,或者作为问题笔记会出现Javascript语法错误。它应该像'{user:null}'一样。 – Pointy 2010-06-13 16:27:58

+0

尖尖的 - 你的增加使这个答案工作。谢谢 – Tony 2010-06-13 16:35:39

0

您没有指定从哪里得到您的to_json。如果您使用的是“json”宝石,nil.to_json会给出"null",这会在您的JS中产生current_user_json = null - 这是有效的。如果它不这样做一些其他的库,最简单的很可能是覆盖to_json所以它产生有效的响应:

class NilClass 
    def to_json 
    "null" 
    end 
end 
+0

这可能不是一个好主意。如果其他东西取决于'NilClass.to_json'的现有行为呢? – 2010-06-13 17:30:33

+0

没错,别的东西可能会打破。但是,返回空值的空字符串可能不一致(我怀疑'[1,nil,3]'被序列化为'[1,null,3]'而不是[1,3]'),并且因此是一个需要修复的bug。如果有什么依赖于这样的行为,那几乎肯定是一种黑客行为,因此,一旦图书馆得到修复,就等待修复。我会提交一个错误报告,并在本地修复该库,直到图书馆得到正确修复 - 或者使用更好的库。 – Amadan 2010-06-13 17:56:55