How to cleanly initialize attributes in Ruby with new?

前端 未结 7 443
夕颜
夕颜 2020-12-06 04:17
class Foo
  attr_accessor :name, :age, :email, :gender, :height

  def initalize params
    @name = params[:name]
    @age = params[:age]
    @email = params[:email]         


        
相关标签:
7条回答
  • 2020-12-06 05:03

    Using all keys from params is not correct, you can define unwilling names. I think it should be kinda white list of names

    class Foo
       @@attributes = [:name, :age, :email, :gender, :height]  
    
       @@attributes.each do |attr|
         class_eval { attr_accessor "#{attr}" }
       end  
    
       def initialize params
         @@attributes.each do |attr|
           instance_variable_set("@#{attr}", params[attr]) if params[attr]
         end  
       end
    end
    
    Foo.new({:name => 'test'}).name #=> 'test'
    
    0 讨论(0)
提交回复
热议问题