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
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:
Here, you are calling
MyApp::Application.configuremethod, 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:
(remember
my_array.each do ... end? It’s a block you pass it. 😉 )Now, that block would be called inside the
configuremethod thanks toyield.yielduses (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:
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(configis a method) to some value, and that sameconfig.something = foois execute insideconfigure.You can learn more about
yieldand blocks here, and on this great book.