wtmyfw
Last Updated: February 25, 2016
·
3.211K
· boriscy

Create Dynamically classes in Ruby

# encoding: utf-8
class MultiTable < ActiveRecord::Base
   belongs_to :user
   validates_presence_of :code, :name
end


# Define classes dynamically
%w(Agreement
   Skill
   Level).each do |klass_name|

  # This can be done on the MultiTable class also
  klass = Class.new(MultiTable) do
    define_method :to_s do
      "#{ code } #{ name }"
    end
  end

  Object.const_set(klass_name, klass)
end

And to not have problems of loading of this Dynamically generated clases just add a file in config/initializers/multi_table.rb

# config/initializers/multi_table.rb
MultiTable