Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/ruby/20.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/.htaccess/6.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Ruby 具有属性的动态类生成_Ruby_Metaprogramming - Fatal编程技术网

Ruby 具有属性的动态类生成

Ruby 具有属性的动态类生成,ruby,metaprogramming,Ruby,Metaprogramming,我正在尝试生成一个具有 dynamic_name = 'Person' Object.const_set(dynamic_name, Class.new {def init(attrs); end}) 我想为这个类生成属性。我试着这样做: Person.class.module_eval { attr_accessor :name} 但是有没有可能将其直接放入init方法中?我还需要为属性设置约束,例如,如上所述的属性名称应为size>0,并允许包含正则表达式/^[A-Z]的字符/attr

我正在尝试生成一个具有

dynamic_name = 'Person'
Object.const_set(dynamic_name, Class.new {def init(attrs); end}) 
我想为这个类生成属性。我试着这样做:

Person.class.module_eval { attr_accessor :name}

但是有没有可能将其直接放入
init
方法中?我还需要为属性设置约束,例如,如上所述的属性名称应为
size>0
,并允许包含正则表达式
/^[A-Z]的字符/

attr\u accessor:name
只不过是DSL语法糖,用于定义
name
name=
方法的普通访问器。它可能没有任何约束。要定义约束,应使用显式setter定义:

attr_reader :name
def name= neu
  raise ArgumentError.new("Name must be not empty") if neu.empty?
  # additional constraints
  @name = neu
end
与上述问题无关的不同之处是:

是否可以将其直接放入
init
方法中

虽然我仍然不明白这些woodoo舞蹈的目的,但有可能:

def init *args
  # native init stuff
  self.class.define_method :name do
    @name
  end unless self.class.method_defined? :name
  self.class.define_method :name= do |neu|
    raise ArgumentError.new("Name must be not empty") if neu.empty?
    # additional constraints
    @name = neu
  end unless self.class.method_defined? :name=
end

希望有帮助。

你为什么要这样做?你想实现什么?我必须用动态名称动态创建类,而且属性也有动态名称和类型!这不是实现这一点的方法吗?什么是
大小
?什么是
name
?无论
size
name
,您的最后一段代码都是无效的。这不是代码,只是对约束的解释。当我使用下面的代码块时,我得到了错误
test。rb:12:in'init':为Person:Class(NoMethodError)调用的私有方法“define\u method”来自test.rb:36:in'
噢,是的。这是私人的。将
self.class.define_方法(:name)
更改为
self.class.send(:define_方法,:name)
。哪一个?所有
define_方法
调用?好的,我得到了它,那么当我这样做
test=Person.new.init'xxx'puts test.name时,我如何访问
name
属性呢`