ruby - Dynamic class generation with attributes -
i trying generate dynamic class with
dynamic_name = 'person' object.const_set(dynamic_name, class.new {def init(attrs); end}) i generate attributes class. tried this:
person.class.module_eval { attr_accessor :name} but possible put directly init method? need set constraints attribute, e.g. attribute name above should of size > 0 , allowed contain characters of regex /^[a-z]/
attr_accessor :name nothing dsl aka syntactic sugar define plain accessors name , name= methods. may not have constraints. define constraints 1 should go explicit setter definition:
attr_reader :name def name= neu raise argumenterror.new("name must not empty") if neu.empty? # additional constraints @name = neu end the different unrelated above question is:
is possible put directly
initmethod?
while still not these woodoo dance for, possible:
def init *args # native init stuff self.class.define_method :name @name end unless self.class.method_defined? :name self.class.define_method :name= |neu| raise argumenterror.new("name must not empty") if neu.empty? # additional constraints @name = neu end unless self.class.method_defined? :name= end hope helps.
Comments
Post a Comment