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.



Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

%d bloggers like this: