如何拒绝或仅允许哈希中的某些键?

How can I reject or allow only certain keys in a Hash?

我有这个方法试图从每个 hashie::mash 对象(每个图像都是一个 hashie::mash 对象)中 select 出某些字段,但不是全部。

  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

你在 Hash#slice:

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

这使您可以 "whitelist" 要包含在返回的哈希中的键。如果要批准的值多于要拒绝的值,则可以相反,使用 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