2016-04-27 76 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