gpt4 book ai didi

ruby-on-rails - Ruby - 根据文件名创建一个类?

转载 作者:太空宇宙 更新时间:2023-11-03 16:08:08 26 4
gpt4 key购买 nike

这是我第一次制作自定义 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/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com