Dynamically create class

Viewed 112

I have the following code:

module City
  class Bus < Base
  end

  class BusOne < Bus; end
  class BusTwo < Bus; end
  class BusSixty < Bus; end
  ....
end

My goal is to create this classes dynamically:

  class BusOne < Bus; end
  class BusTwo < Bus; end
  class BusSixty < Bus; end
  ...

That's why I tried:

module City
  class Bus < Base
    DIVISON = [:one, :two, :sixty]
  end

  ....
  Bus::DIVISONS.each do |division|
    class "Bus#{division.capitalize}".constantize < Bus; end
  end
end

But I get this error:

unexpected '<', expecting &. or :: or '[' or '.' (SyntaxError)

What do I wrong? Thanks

2 Answers

Works with:

City.send(:const_set, "Bus#{division.capitalize}", Class.new(Bus))

This is a variant of John's answer, mainly to show the use of send is not essential.

module City
  class Bus
    def i_am
      puts "this is class #{self.class}"
    end
  end
end

["BusOne", "BusTwo", "BusSixty"].each do |class_name|
    City.const_set(class_name, Class.new(City::Bus))
end

City::BusOne.new.i_am
this is class City::BusOne

City::BusTwo.new.i_am
this is class City::BusTwo

City::BusSixty.new.i_am
this is class City::BusSixty
Related