Forcing attr_writer to a type?

(Malte Milatz) #1

Daniel Schierbeck wrote:

Is it even possible to write a method that acts like

    attr_writer :blah { |input| input.to_f }

Here is my try, which seems to work:

class Class
  def attr_accessor(attr)
    attr = attr.to_str if attr.respond_to? :to_str
    attr = attr.id2name if attr.respond_to? :id2name
    attr_reader(attr)
    if not block_given?
      attr_writer(attr)
    else
      define_method(attr + '=') do |value|
        instance_variable_set('@' + attr, yield(value))
      end
    end
  end
end

class Test
  attr_accessor :blah do |x| x.to_f end
  attr_accessor :bla
end

t = Test.new
t.bla = 10
p t.bla
t.blah = 10
p t.blah

# Malte