Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Specify attribute list in attr_accessor with method call

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.

like image 936
maximus ツ Avatar asked May 15 '13 10:05

maximus ツ


Video Answer


2 Answers

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.

like image 142
maximus ツ Avatar answered Oct 06 '22 07:10

maximus ツ


One way to do this without incurring a warning:

class MyClass
    ATTR_LIST = [:x1, :y1, :x2, :y2]
    attr_accessor(*ATTR_LIST)
end
like image 33
Joshua Swink Avatar answered Oct 06 '22 09:10

Joshua Swink