You don't need a constant, but I don't think you can exclude a character in a string:
class Example attr_reader :name, :age def initialize args args.each do |k,v| instance_variable_set("@#{k}", v) unless v.nil? end end end #=> nil e1 = Example.new :name => 'foo', :age => 33 #=> #<Example:0x3f9a1c @name="foo", @age=33> e2 = Example.new :name => 'bar' #=> #<Example:0x3eb15c @name="bar"> e1.name #=> "foo" e1.age #=> 33 e2.name #=> "bar" e2.age #=> nil
By the way, you can take a look (if you haven't already) in the Struct class generator class, it looks a bit like what you are doing, but not hash type initialization (but, I think, it would not be easy to create the corresponding generator class).
HasProperties
Trying to implement hurikhan idea, here is what I came to:
module HasProperties attr_accessor :props def has_properties *args @props = args instance_eval { attr_reader *args } end def self.included base base.extend self end def initialize(args) args.each {|k,v| instance_variable_set "@#{k}", v if self.class.props.member?(k) } if args.is_a? Hash end end class Example include HasProperties has_properties :foo, :bar # you'll have to call super if you want custom constructor def initialize args super puts 'init example' end end e = Example.new :foo => 'asd', :bar => 23 p e.foo #=> "asd" p e.bar #=> 23
Since I am not good at metaprogramming, I responded to the community wiki so that anyone can change the implementation.
Struct.hash_initialized
Struct deployed the answer to Marc-Andre, here is the general Struct method for creating initialized hash classes:
class Struct def self.hash_initialized *params klass = Class.new(self.new(*params)) klass.class_eval do define_method(:initialize) do |h| super(*h.values_at(*params)) end end klass end end # create class and give it a list of properties MyClass = Struct.hash_initialized :name, :age # initialize an instance with a hash m = MyClass.new :name => 'asd', :age => 32 pm #=>#<struct MyClass name="asd", age=32>
Mladen Jablanović Apr 21 '10 at 7:26 2010-04-21 07:26
source share