动态创建类

时间:2017-10-04 16:54:13

标签: ruby-on-rails ruby ruby-on-rails-3 ruby-on-rails-4 ruby-on-rails-5

我有以下代码:

module City
  class Bus < Base
  end

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

我的目标是动态创建这些类:

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

这就是我尝试的原因:

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

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

但是我收到了这个错误:

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

我错了什么? 感谢

2 个答案:

答案 0 :(得分:1)

适用于:

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

答案 1 :(得分:1)

这是约翰答案的变体,主要是为了表明使用send并非必不可少。

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