1

I have three Ruby files in the same directory:

classthree.rb
otherclass.rb
samplecode.rb

Here are the contents of classthree.rb:

require './samplecode.rb'
require './otherclass.rb'

class ClassThree

  def initialize()
    puts "this class three here"
  end

end

Here are the contents of samplecode.rb:

require './otherclass.rb'
require './classthree.rb'

class SampleCode

  $smart = SampleCode.new
  @sides = 3
  @@x = "333"

  def ugly()
    g = ClassThree.new
    puts g
    puts "monkey see"
  end


  def self.ugly()
    s = SampleCode.new
    s.ugly
    puts s
    puts $smart
    puts "monkey see this self"
  end

  SampleCode.ugly

end

Here are the contents of otherclass.rb:

require './samplecode.rb'
require './classthree.rb'

END {
  puts "ending"
}

BEGIN{
  puts "beginning"
}

class OtherClass

  def initialize()
    s = SampleCode.new
    s.ugly
  end

end

My two questions are:

  1. There has to be a better way than require './xyz.rb' for every class in the directory. Isn't there something like require './*.rb'?
  2. When I run ruby otherclass.rb I get the following output:

enter image description here

Why do I get "beginning" and "ending" twice each??

the Tin Man
  • 158,662
  • 42
  • 215
  • 303
Alexander Mills
  • 90,741
  • 139
  • 482
  • 817
  • Extract from your code whatever that is not related to your point. Show the minimum required to show your point. – sawa Mar 20 '14 at 01:17
  • 1
    Consider converting your project to a Ruby gem. Rubygems is a module system for Ruby that works by managing the library search path. Hacking around `$LOAD_PATH` should never be needed. – Matheus Moreira Mar 20 '14 at 01:40
  • 1
    Also see [this](http://stackoverflow.com/questions/735073/best-way-to-require-all-files-from-a-directory-in-ruby) question. – user2422869 Mar 20 '14 at 03:52

1 Answers1

4

At 1 - The best way to deal with it is to create another file. You can call it environment.rb or initialize.rb, and it would require all the needed files.

$LOAD_PATH.unshift File.dirname(__FILE__)

require 'samplecode.rb'
require 'classthree.rb'
require 'classthree.rb'

Now you only need to require this file once on the start of the application.

At 2 - You started from file 'otherclass.rb'. It displays the first 'beginning' bit and then it loads samplecode.rb file. At this point, 'otherclass.rb' has not been loaded yet - it was not required by any other file. hence samplecode.rb is rerunning whole otherclass.rb, which is being required there. Rerunning doesn't reload 'samplecode.rb' as it was already required (require checks first whether file was or was not required). That's why you're seeing those messages twice.

BroiSatse
  • 44,031
  • 8
  • 61
  • 86