tags:

views:

73

answers:

1

I have seen the run_once method 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...

+1  A: 

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
mikej