小编mr.*_*The的帖子

Ruby"定义了吗?" 操作员工作错了?

所以,我们有代码:

class Foo
  def bar
    puts "Before existent: #{(defined? some_variable)}"
    puts "Before not_existent: #{(defined? nonexistent_variable)}"

    raise "error"

    some_variable = 42
  rescue
    puts "exception"
  ensure
    puts "Ensure existent: #{(defined? some_variable)}"
    puts "Ensure not_existent: #{(defined? nonexistent_variable)}"
  end
end
Run Code Online (Sandbox Code Playgroud)

并从irb调用它:

> Foo.new.bar
Run Code Online (Sandbox Code Playgroud)

而且,这将返回:

Before existent:
Before not_existent:
exception
Ensure existent: local-variable
Ensure not_existent:
=> nil
Run Code Online (Sandbox Code Playgroud)

现在问题 - 为什么?我们之前提出异常不是some_variable定义.为什么这样工作?为什么some_variable在ensure块中定义?(顺便说一下,它定义为零)

更新: 感谢@Max的回答,但如果我们更改代码以使用实例变量:

class Foo
  def bar
    puts "Before existent: #{(defined? @some_variable)}"
    puts "Before not_existent: #{(defined? @nonexistent_variable)}"

    raise …
Run Code Online (Sandbox Code Playgroud)

ruby behavior exception defined

8
推荐指数
1
解决办法
198
查看次数

在Rabl视图中片段缓存?

我读了rabl缓存文档,我不知道如何缓存代码片段.我有这样的观点(有更多的代码,但我为了简单起见删除了它):

object @video

attributes :id, :user_id, :event_id

child :event do
  attributes :id
  node(:name) { |event| event.name }
end

child :user do
  attributes :id
end
Run Code Online (Sandbox Code Playgroud)

我想缓存:活动孩子两个小时.我怎样才能做到这一点?

我正在使用rabl(0.7.6),rails(3.2.0),ruby(1.9.3p125)

ruby caching ruby-on-rails ruby-on-rails-3 rabl

3
推荐指数
1
解决办法
1128
查看次数