Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to make 'attr_reader' or 'attr_writer' for all class variables at one time?

I am using Ruby on Rails 3 and, since I have a declared a class with a lot of variables, I would declare all 'attr_reader' or 'attr_writer' for those class variables at one time.

I tryed

class Persone
  attr_reader :all

  def initialize(name, surname, ...)
    @name = name
    @surname = surname
    ... # A lot of variables!
  end
end

but that doesn't work.

like image 765
user502052 Avatar asked Feb 24 '23 23:02

user502052


2 Answers

class Persone
  INSTANCE_VARS = [:name,:surname]
  attr_reader *INSTANCE_VARS

  def initialize(*params)
    params.each_with_index do |param,index|
      instance_variable_set("@"+INSTANCE_VARS[index].to_s,param)
    end
  end
end
like image 89
zetetic Avatar answered Apr 08 '23 01:04

zetetic


I thing you should use:

attr_accesor :name, :surname, ...

def initialize(name, surname, ...)
  @name = name
  @surname = surname
  ...
end

This way you get a setter and a getter in only one step, but you still have to enum all that variable names.

like image 30
Emmanuel Valle Avatar answered Apr 08 '23 01:04

Emmanuel Valle