2012-09-27 91 views
0

我有我的主要模式中的一個方法,應根據設定的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哈希指定的值?

回答

3

使用send而不是eval。此代碼應該可以正常工作。

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