Brand
Brand

Reputation: 1701

how does this ruby code work for setting configuration

I see ruby code that looks like the following. It seems to be some sort of idiom for creating configuration or settings but I don't really understand it. Also, how would the Application.configure part of this code look?

MyApp::Application.configure do
  config.something = foo
  config.....
  config....
  .
  config....
end

Upvotes: 2

Views: 518

Answers (2)

Samy Dindane
Samy Dindane

Reputation: 18706

First of all, that configuration way is not specific to Ruby ; it's the applications (or libraries, gems) that choose to use it or not.

To explain you what does that code do, I'll take your snippet as an example:

MyApp::Application.configure do
  config.something = foo
end

Here, you are calling MyApp::Application.configure method, with no parameter. After the call, you're giving it a block.

You can think of blocks as a piece of code that you can use however you want.
They can be written in one single line or many:

{ puts 'hello' }
{ |param| puts param } # with passing it a param

# or 

do |param|
  puts param
end

(remember my_array.each do ... end? It's a block you pass it. ;) )

Now, that block would be called inside the configure method thanks to yield.

yield uses (or executes) the instructions of the block that has been passed to the method.

Example: Let's define a method with a yield inside of it:

def hello
  puts "Hello #{yield}"
end

If you call this method, you'd get a 'hello': no block given (yield) (LocalJumpError)'.

You need to pass it a block: hello { :Samy }.
The result would then be Hello Samy. As you can see, it simply used what was in the block passed to the method.

That's exactly what's happening in the Rails configuration code. You simply set config.something (config is a method) to some value, and that same config.something = foo is execute inside configure.

You can learn more about yield and blocks here, and on this great book.

Upvotes: 4

Jesse Wolgamott
Jesse Wolgamott

Reputation: 40277

The part from "do" until "end" is called a block, and is getting passed to the configure class method on Application. (all ruby methods can accept arguments and a block)

so the Application.configure method is creating a configuration object with a set of defaults, and then calling the block. The block is then setting the values you see, having the effect of overriding them.

It's then setting that configuration object as a class variable (like a global variable) so that other classes can use the configuration object later in the application lifecycle.

Hope that simplified description helps!

Upvotes: 2

Related Questions