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 init method?

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

Popular posts from this blog

asp.net mvc - SSO between MVCForum and Umbraco7 -

Python Tkinter keyboard using bind -

ubuntu - Selenium Node Not Connecting to Hub, Not Opening Port -