开发者

What is run_once in ruby?

开发者 https://www.devze.com 2022-12-15 12:52 出处:网络
I have seen the run_once method开发者_如何学JAVA in some code like run_once do [:hello, :core, :gems, :plugins, :lib, :initializers, :routes, :app, :helpers].each do |f|

I have seen the run_once method开发者_如何学JAVA in some code like

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

I found it in Kernel, but not sure what it does... something to do with running once I guess...


Assuming it is the Mack Facets run_once method we're talking about, here is its source:

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

You would call the method with no arguments but passing a block. run_once takes the first entry from the call stack (caller.first) to determine the point in code from which it is being called. It will only yield to the block if run_once hasn't yet been called from this call point (tracked by keeping the list of call points in the global array $__already_run_block)

e.g. it could be used along these lines:

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
0

精彩评论

暂无评论...
验证码 换一张
取 消