Jeff Storey
Jeff Storey

Reputation: 57222

Ruby module defined in block?

I've seen a ruby block that looks something like:

Vagrant::Config.run do |config|

   module MyModule      
   end

end

What is the effect of declaring a module like that inside of a block?

EDIT:

Specifically I had a block to do some cleanup when the VM was terminated, and it looks like

Vagrant::Config.run do |config|

  # vagrant config stuff

   module Vagrant
     module Provisioners
      class ChefClient < Chef
        def cleanup
          # cleanup here
        end
      end
    end
  end
end

If the module is defined outside of the Vagrant::Config block I get the error

'<module:Provisioners>': uninitialized constant Vagrant::Provisioners::Chef (NameError)

And I'm not sure why declaring the module inside the run block made a difference.

Upvotes: 1

Views: 396

Answers (2)

tadman
tadman

Reputation: 211750

It will will conditionally define the module. Remember that blocks are not necessarily executed, it is up to the target method to decide.

While your particular example is perfectly valid Ruby, organizing things like that can lead to confusion. It would be better to have that defined outside of the block for reasons of clarity.

Upvotes: 1

the Tin Man
the Tin Man

Reputation: 160631

Among other things, Modules are useful to provide a new namespace for variables and constants. I'd say that was the reason.

Upvotes: 0

Related Questions