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

后端 未结 6 571
遇见更好的自我
遇见更好的自我 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:26

    There's no built-in way to get such a list. The attr_* functions essentially just add methods, create an instance variable, and nothing else. You could write wrappers for them to do what you want, but that might be overkill. Depending on your particular circumstances, you might be able to make use of Object#instance_variable_defined? and Module#public_method_defined?.

    Also, avoid using eval when possible:

    def initialize(opts)
      opts.delete_if{|opt,val| not the_list_of_readers.include?(opt)}.each do |opt,val|
        instance_variable_set "@#{opt}", val
      end
    end
    

提交回复
热议问题