2010-01-03 80 views
1

我已經看到了一些代碼的run_once方法類似ruby​​中的run_once是什麼?

run_once do 
    [:hello, :core, :gems, :plugins, :lib, :initializers, :routes, :app, :helpers].each do |f| 
    require File.join_from_here('mack', 'boot', "#{f}.rb") 
    end 
end 

我發現它在內核中,但不知道它做什麼?是與運行一次,我猜...

+0

這是在Mack框架的上下文嗎? (http://api.mackframework.com/mack/) – mikej 2010-01-03 00:21:45

回答

1

假設這是我們正在談論的Mack Facets run_once方法,這裏是它的源:

def run_once 
    path = File.expand_path(caller.first) 
    unless ($__already_run_block ||= []).include?(path) 
    yield 
    $__already_run_block << path 
    end 
    # puts "$__already_run_block: #{$__already_run_block.inspect}" 
end 

你會調用不帶參數的方法,但經過一個街區。 run_once將從調用堆棧(caller.first)的第一個條目中確定調用它的代碼點。如果run_once還沒有從該呼叫點被呼叫(通過保持呼叫點在全球陣列中的列表$__already_run_block

例如,它可以沿着這些線使用:

def initialise 
    run_once do 
    # any code here will only execute the first time initialise is called 
    # and will be skipped on subsequent calls to initialise 
    end 
end