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.
requiredoes 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 aputsstatement.Try this as a simple example. Create a file
hello.rbcontainingputs "Hello World"then go into irb:Next, try this example of a simple class with some executable code in its body. Create a file
hello2.rbcontaining:then require this from irb:
Going back to
bin/rails, take a look at the source for rails/cli in Github to follow the chain of how it works.