Initialize a Ruby class from an arbitrary hash, but only keys with matching accessors

后端 未结 6 591
遇见更好的自我
遇见更好的自我 2021-01-01 04:00

Is there a simple way to list the accessors/readers that have been set in a Ruby Class?

class Test
  attr_reader :one, :two

  def initialize
    # Do someth         


        
6条回答
  •  感情败类
    2021-01-01 04:44

    Accessors are just ordinary methods that happen to access some piece of data. Here's code that will do roughly what you want. It checks if there's a method named for the hash key and sets an accompanying instance variable if so:

    def initialize(opts)
      opts.each do |opt,val|
        instance_variable_set("@#{opt}", val.to_s) if respond_to? opt
      end
    end
    

    Note that this will get tripped up if a key has the same name as a method but that method isn't a simple instance variable access (e.g., {:object_id => 42}). But not all accessors will necessarily be defined by attr_accessor either, so there's not really a better way to tell. I also changed it to use instance_variable_set, which is so much more efficient and secure it's ridiculous.

提交回复
热议问题