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
    if not block_given?
      define_method(attr + '=') do |value|
        instance_variable_set('@' + attr, yield(value))

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

t =
t.bla = 10
p t.bla
t.blah = 10
p t.blah

# Malte