Accessing attr_accessor attributes with variable

689 views Asked by At

below question is about selecting the attributes enabled by "attr_accessor" for an object. Example:

class Openhour < ActiveRecord::Base

  belongs_to :shop    
  attr_accessor :monday, :tuesday, :wednesday, :thursday, :friday, :saturday, :sunday

end

This allows me to

week = Openhour.new
week.monday = "Open"
week.tuesday = "Closed"

My question: How can I select the attr_accessors by using a variable from a loop? In below case I would use dayname to select the attr_accessor.

@schedules.each do |schedule|
   %w(monday tuesday wednesday thursday friday saturday sunday).each_with_index do |dayname,dayname_index|

      week.dayname = schedule.day == dayname_index ? "Open" : "Closed"

   end
end

This, however, would result in

*** NoMethodError Exception: undefined method `dayname' for #<Model>

Thanks in advance!

1

There are 1 answers

0
Lukas Baliak On BEST ANSWER

you can use

 week.send("#{dayname}=", schedule.day == dayname_index ? "Open" : "Closed")

Or you can work with it like instance_variables

week.instance_variable_set("@#{dayname}", schedule.day == dayname_index ? "Open" : "Closed")