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

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

    Try something like this:

    class Test
      attr_accessor :foo, :bar
    
      def initialize(opts = {})
        opts.each do |opt, val|
          send("#{opt}=", val) if respond_to? "#{opt}="
        end
      end
    end
    
    test = Test.new(:foo => "a", :bar => "b", :baz => "c")
    
    p test.foo # => nil
    p test.bar # => nil
    p test.baz # => undefined method `baz' for # (NoMethodError)
    

    This is basically what Rails does when you pass in a params hash to new. It will ignore all parameters it doesn't know about, and it will allow you to set things that aren't necessarily defined by attr_accessor, but still have an appropriate setter.

    The only downside is that this really requires that you have a setter defined (versus just the accessor) which may not be what you're looking for.

提交回复
热议问题