这是我第一次制作自定义 Rails 生成器,我希望能够根据传递给生成器的参数在模板中创建动态类,但我不知道如何以及如何正确格式化它。
class Achievements::__FILE__ < Achievement
end
这是我想要创建的生成类,下面是生成器。另外,我是否在生成器中创建了“成就”目录?
module Achiever
module Generators
class AchievementGenerator < Rails::Generators::Base
source_root File.expand_path('../templates', __FILE__)
argument :award, :type => :string
def generate_achievement
copy_file "achievement.rb", "app/models/achievement/#{file_name}.rb"
end
private
def file_name
award.underscore
end
end
end
end
最佳答案
使用Module#const_set 。它会自动包含到对象中,因此您可以执行以下操作:
foo.rb
# Defining the class dynamically. Note that it doesn't currently have a name
klass = Class.new do
attr_accessor(:args)
def initialize(*args)
@stuff = args
end
end
# Getting the class name
class_name = ARGV[0].capitalize
# Assign it to a constant... dynamically. Ruby will give it a name here.
Object.const_set(class_name, klass)
# Create a new instance of it, print the class's name, and print the arguments passed to it. Note: we could just use klass.new, but this is more fun.
my_klass = const_get(class_name).new(ARGV[1..-1])
puts "Created new instance of `" << my_klass.class << "' with arguments: " << my_klass.args.join(", ")
我还没有尝试过这段代码,但它应该会产生类似的结果:
$ ruby foo.rb RubyRules pancakes are better than waffles
Created new instance of `RubyRules' with arguments: pancakes, are, better, than, waffles
此外,const_set
的第一个参数绝对必须以大写字母数字字符开头(就像静态定义常量一样),否则 Ruby 会产生类似的错误的:
NameError: wrong constant name rubyRules
--- INSERT STACKTRACE HERE ---
关于ruby-on-rails - Ruby - 根据文件名创建一个类?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9474308/