2016-04-27 77 views
0

我有这种方法试图从每个hashie :: mash对象(每个图像是一个hashie :: mash对象)中选择某个字段,但不是全部。如何拒绝或只允许哈希中的某些密钥?

def images 
     images = object.story.get_spree_product.master.images 
     images.map do |image| 
      { 
      position: image["position"], 
      attachment_file_name: image["attachment_file_name"], 
      attachment_content_type: image["attachment_content_type"], 
      type: image["type"], 
      attachment_width: image["attachment_width"], 
      attachment_height: image["attachment_height"], 
      attachment_updated_at: image["attachment_updated_at"], 
      mini_url: image["mini_url"], 
      small_url: image["small_url"], 
      product_url: image["product_url"], 
      large_url: image["large_url"], 
      xlarge_url: image["xlarge_url"] 
      } 
     end 
     end 

有没有更简单的方法来做到这一点?

图像是一个hashie :: mash对象的数组。

object.story.get_spree_product.master.images.first.class 
Hashie::Mash < Hashie::Hash 
[15] pry(#<Api::V20150315::RecipeToolSerializer>)> object.story.get_spree_product.master.images.count 
2 

回答

6

Hash#slice后:

def images 
    images = object.story.get_spree_product.master.images 
    images.map do |image| 
    image.slice("position", "attachment_file_name", "...") 
    end 
end 

这可以让你 “白名单” 键在返回哈希包括。如果有更多值需要批准而不是拒绝,那么您可以做相反的事情,只列出要使用Hash#except拒绝的键。

在这两种情况下,你可能会发现更容易地允许密钥列表保存为一个单独的数组,并与*图示它:

ALLOWED_KEYS = %w(position attachment_file_name attachment_content_type ...) 

def images 
    object.story.get_spree_product.master.images.map do |image| 
    image.slice(*ALLOWED_KEYS) 
    end 
end 
+1

我想这是一个Rails应用程序? 'slice'和'except'是加载Rails时添加到Hash类的方法;它们不在Ruby的Hash类中。 –

+1

@KeithBennett原始代码引用了[Spree](https://github.com/spree/spree),它是一个完整的Rails应用程序。 – tadman