Specify attribute list in attr_accessor with method call
Asked Answered
P

3

11

I want to create large number of attributes which can be done with ease if constructed with method call like this,

 attr_accessor :attr_list 

 def attr_list
   [:x1, :y1, :x2, :y2]   
 end

This is not working. Is there any other way to achieve this?

Any help will be appreciated.

Preparative answered 15/5, 2013 at 10:49 Comment(0)
P
18

Figured it out,

def self.attr_list
 [:x1, :y1, :x2, :y2]   
end

attr_accessor *attr_list 

Explanation:

As attr_accessor is a method call which expects parameters list. So we can not pass array as it is. (*) will convert array into parameters list.

Just need to define a class method returning array of attribute list passed to attr_accessor.

Works well with attr_accessible(or anything similar) as well.

Preparative answered 12/6, 2013 at 18:8 Comment(0)
P
6

One way to do this without incurring a warning:

class MyClass
    ATTR_LIST = [:x1, :y1, :x2, :y2]
    attr_accessor(*ATTR_LIST)
end
Parsee answered 26/1, 2016 at 23:46 Comment(0)
A
3

The accepted solution produces a ruby warning:

'*' interpreted as argument prefix

An alternative would be to do something like this:

def attr_list
  [:x1, :y1, :x2, :y2]   
end

attr_list.each { |attr| attr_accessor attr }

or

ATTR_LIST = [:x1, :y1, :x2, :y2]
ATTR_LIST.each { |attr| attr_accessor attr }
Amateurism answered 25/2, 2015 at 1:5 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.