如何在 Ruby on Rails 中声明全局变量?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/30321752/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How can I declare a global variable in Ruby on Rails?
提问by do_Ob
How can I declare a global variable in Ruby on Rails?
如何在 Ruby on Rails 中声明全局变量?
My sample code:
我的示例代码:
in my controller#application.rb:
在我的controller#application.rb:
def user_clicked()
@current_userid = params[:user_id]
end
in my layout#application.html.hamlI have sidebar with this link:
在我的layout#application.html.haml侧边栏中,我有这个链接:
= link_to "John", user_clicked_path(:user_id => 1)
= link_to "Doe", user_clicked_path(:user_id => 2)
= link_to "View clicked user", view_user_path
in my views#view_user.html.haml:
在我的views#view_user.html.haml:
%h2 @current_userid
I want to declare a global variable that can modify my controller and use it anywhere, like controller, views, and etc. The above is only a sample scenario. If I click the John or Doe link, it will send a user_idto the controller and when I click the "View clicked user" link, it will display the last clicked link. It is either John=1or Doe=2.
我想声明一个全局变量,它可以修改我的控制器并在任何地方使用它,如控制器、视图等。以上只是一个示例场景。如果我点击 John 或 Doe 链接,它会向user_id控制器发送一个,当我点击“查看点击的用户”链接时,它将显示最后点击的链接。它是John=1或Doe=2。
Of course if I click the "View clicked user" link first, it will display nil.
当然,如果我先点击“查看点击的用户”链接,它会显示nil.
回答by max
In Ruby global variables are declared by prefixing the identifier with $
在 Ruby 中,全局变量是通过在标识符前加上前缀来声明的 $
$foo = 'bar'
Which you rarely see used for a number of reasons. And it's not really what you are looking for.
由于多种原因,您很少看到使用它。这并不是您真正要寻找的。
In Ruby instance variables are declared with @:
在 Ruby 实例变量中声明为@:
class DemoController
def index
@some_variable = "dlroW olleH"
@some_variable = backwards
end
private
def backwards
@some_variable.reverse
end
end
Rails automatically passes the controller's instance variables to the view context.
Rails 自动将控制器的实例变量传递给视图上下文。
# /app/views/demos/index.html.haml
%h1= @some_variable
Guess what it outputs and I'll give you a cookie.
猜猜它输出什么,我会给你一个饼干。
In your example @global_variableis nil since controller#sample_1is not called - the request would go through controller#sample_2.
在你的例子中@global_variable是 nil 因为controller#sample_1没有被调用 - 请求会通过 controller#sample_2。
def sample_2
@global_variable = "Hello World"
end

