How do I set an attr_accessor for a dynamic instance variable?

可紊 提交于 2019-12-18 10:24:39

问题


I dynamically created an instance variable within my class:

class Mine
  attr_accessor :some_var

  def intialize
    @some_var = true
  end

  def my_number num
    self.instance_variable_set "@my_#{num}", num
  end
end

How do I make @my_#{num} now as an attr value?

e.g. I want to be able to do this:

dude = Mine.new
dude.my_number 1
dude.my_1
=> 1

回答1:


this answer doesn't pollutes the class space, example.. if i do mine.my_number 4 then the other instances of Mine will not get the my_4 method.. this happens because we use the singleton class of the object instead of the class.

class Mine
  def my_number num
    singleton_class.class_eval { attr_accessor "my_#{num}" }
    send("my_#{num}=", num)
  end
end

a = Mine.new
b = Mine.new
a.my_number 10 #=> 10
a.my_10 #=> 10
b.my_10 #=> NoMethodError



回答2:


This can be accomplished using __send__. Here:

class Mine
  attr_accessor :some_var

  def intialize
    @some_var = true
  end

  def my_number num
    self.class.__send__(:attr_accessor, "my_#{num}")
    self.__send__("my_#{num}=", num)
  end
end

dude = Mine.new
dude.my_number 1
puts dude.my_1

=> 1



回答3:


Easy. You can dynamically define the attribute reader inside the my_number method:

  def my_number num
     self.instance_variable_set "@my_#{num}", num
     self.class.class_eval do
        define_method("my_#{num}") { num }
     end
  end

see if that works for you




回答4:


There's one problem with the two methods here... if an instance variable is set in one instance, its accessor will be available to all instances, because you're defining methods on self.class instead of on self.

dude = Mine.new
dude.my_number 1
puts dude.my_1
dudette = Mine.new
dudette.my_1 = 2    # works, but probably shouldn't
dudette.my_number 2
dude.my_2 = 3       # works, but probably shouldn't

What you probably want to do is modify only the instance that has the instance variable:

class Mine
  # ...
  def my_number num
    class << self
      attr_accessor "my_#{num}"
    end
    self.send("my_#{num}=", num)
  end
end

This way, instance variables only get accessors on the objects they were created for. I also didn't bother with instance_variable_set, because if you're setting an accessor, then I think it reads better to just reuse that. But that's a style call. The big deal here is calling class << self instead of self.class.




回答5:


You may want to use OpenStruct:

require "ostruct"

class Mine < OpenStruct
end

dude = Mine.new
dude.my_number = 1
dude.my_number # => 1

I don't know why you'd want dude.my_1 to return 1 - isn't that giving you back what you already have?




回答6:


older thread, but I found it useful thank you. Here is the code Dorkus Prime's answer, but also taking instance vars from name\values in a hash

@cookies = browser.cookies.to_a

@cookies.each do |cookie|
self.class.__send__(:attr_accessor, "#{cookie[:name]}")
self.__send__("#{cookie[:name]}=",cookie[:value])
end



回答7:


Yet another solution to add to the pile, define_singleton_method:

class Mine
  def my_number num
    define_singleton_method("num_#{num}") { num }
  end
end

One side effect of all of these solutions is that if you call it multiple times with different numbers, you end up with a bunch of methods on your object:

dude = Mine.new
dude.my_number 1
dude.my_number 5
dude.my_1
=> 1
dude.my_5
=> 5

We can fix this by removing the old method:

class Mine
  def my_number num
    old_num = @num
    if @num
      # need to use `old_num` local variable
      # instance var scope is different inside `class_eval`
      singleton_class.class_eval { remove_method("num_#{old_num}") }
    end

    @num = num

    define_singleton_method("num_#{num}") { @num }
  end
end


来源:https://stackoverflow.com/questions/4964179/how-do-i-set-an-attr-accessor-for-a-dynamic-instance-variable

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!