user2053865
user2053865

Reputation:

Rails code segment explained

I am working on an app which has the below code:

def app
  @app ||= begin
    if !::File.exist? options[:config]
      abort "configuration #{options[:config]} not found"
    end

    app, myoptions = Rack::Builder.parse_file(self.options[:config], opt_parser)
    self.myoptions.merge! myoptions
    app
  end
end

I am struggling to get my head around several parts of it..

@app||= begin...end

Does this mean that if @app does not exist the block is run?

app ,options = rack::builder

What does the comma do to it?

Please help

Upvotes: 2

Views: 70

Answers (2)

Jahan Zinedine
Jahan Zinedine

Reputation: 14874

@Craig-Taub ansewered the question,
I just want to add some notes:

Ruby commands are expressions which means they return value and you can assign them to variables.
You can read more about expressions and statements on Wikipedia and PragProg.

Second is that when you return more than one value in a code block, Ruby will wrap it into a simple array and return it to the caller.
That's why it works like that.

Upvotes: 1

Craig Taub
Craig Taub

Reputation: 4179

Your first assumptions was correct, it does say that if @app is nil, set it to whatever is returned in the block delimited with begin, end.

Regarding the comma, it works like this:

avar, bvar = "atest", "btest"

If you look at the source for Rack:Builder.parse_file then you will notice the last line

return app, options

So it is returning two values.

Hope that helps

Upvotes: 2

Related Questions