Dynamically Loaded Classes

20 02 2008

Defining the class name of rails models when we’ve already named the file didn’t seem very DRY to me. So I wanted to find out if I could load files into a class named after the file (ie. Products.rb gets loaded in to Product class)

#!/usr/bin/env ruby

# Loop over all ruby files in the classes directory
Dir["classes/*.rb"].map do |file_name|
  # Save file name without extention or directories
  class_name = file_name[/[^\/]*(?=\.)/].to_sym

  # Execute the contents of the file inside a blank object
  class_object = Class.new

  # Bind the class to the name at the highest level
  Kernel.const_set(class_name, class_object)

This assumes that you have a bunch of ruby files inside a sub directory called ‘classes’ and all your ruby files have ‘.rb’ extension.