views:

34

answers:

2

Now, I've used Rails enough to know what the rails command does, but how it does it interests me.

The bin/rails file (from github) is as follows:

#!/usr/bin/env ruby

begin
  require "rails/cli"
rescue LoadError
  railties_path = File.expand_path('../../railties/lib', __FILE__)
  $:.unshift(railties_path)
  require "rails/cli"
end

As far as I know (and please correct me if I'm wrong), require doesn't run code, just loads classes etc.

I could also not find the rails directory in the root of them gem, so I'm a little confused where that's hiding as well.

Thanks.

+3  A: 

require does run code. This will include any code outside of any classes and modules in the file being required plus any executable code in classes and modules that is outside of method declarations. As neutrino has said, the ruby interpreter is running the code in the file being required in order to define the classes in the source. However this might be a bit clearer if you try it out with something that has an obvious side effect like a puts statement.

Try this as a simple example. Create a file hello.rb containing puts "Hello World" then go into irb:

irb(main):001:0> require 'hello'
Hello World
=> true

Next, try this example of a simple class with some executable code in its body. Create a file hello2.rb containing:

class Hello
  puts "class Hello being defined"
end

then require this from irb:

irb(main):001:0> require 'hello2'
class Hello being defined
=> true

Going back to bin/rails, take a look at the source for rails/cli in Github to follow the chain of how it works.

mikej
Great answer, thanks. What does load do in that case?
thomasfedb
+3  A: 

All ruby code is executable code. Class/module/method definitions are also executed by the interpreter, so when you say that require loads classes, it's true because loading a class means executing its code :)

Here is the file you are looking for: cli.rb. It's in railties.

neutrino