动态指定返回的值

时间:2012-09-27 12:52:51

标签: ruby-on-rails ruby

我的主模型中有一个方法,它应该根据set params返回特定的值:

def self.retrieve_profiles( params )

  case params[:view]

    when 'image_only'
      fields = %w{ avatar }

    when 'profile_minimal'
      fields = %w{ avatar username age }

    when 'profile_medium'
      fields = %w{ avatar username age first_name last_name bio relationship_status seeking }

    when 'profile_extended'
      fields = %w{ avatar username age first_name last_name bio relationship_status seeking country city photos }

  end    

  profiles = Profile.that_has_photos
  profiles = profiles.where( :country_id => params['country'] ) unless params['country'].nil?    
  profiles = profiles.order( "RAND()" ).limit( params['count'] )      

  # works fine up to here (returns all fields)

  profiles.each do |a|
    fields.each do |field|
      puts a.eval(field)
    end
  end

  # above block makes it fail (private method `eval' called)

end

我的问题是:如何仅返回fields哈希指定的值?

1 个答案:

答案 0 :(得分:3)

使用send代替eval。这段代码应该可以正常工作。

  profiles.each do |a|
    fields.each do |field|
      puts a.send(field)
    end
  end