From: Mike Cahill Date: 2009-02-11T13:01:25+09:00 Subject: redefining @my_attr= I want to write a generic validator that ensures an attr value is in a list before assigning, and if not, assigns a default. It works for self.attrib='value', and Dummy.new.attrib='value', but not @attrib='value' within the class. Any way to do that? Here's the code: module Validator def validate_is_member_of( attrib, list, default ) original_method = instance_method( "#{attrib}=".to_sym ) define_method( "#{attrib}=".to_sym ) do |val| instance_variable_set( "@#{attrib}", (list.include?( val ) ? val : default )) end end end class Dummy extend Validator attr_accessor :name, :type validate_is_member_of :type, [ :fruit, :veggie, :dairy ], :fruit def initialize( name, type ) @name = name @type = type end end good = Dummy.new('good', :veggie ) # => ... @type=:veggie good.type = :ice_cream # => ... @type=:fruit. i know i overwrote a valid value. it's ok. bad = Dummy.new('bad', :chocolate ) # => ... @type=:chocolate; I want :fruit here. -- Posted via http://www.ruby-forum.com/.