Techioz Blog

ハッシュ内の特定のキーのみを拒否または許可するにはどうすればよいですか?

概要

各 hachie::mash オブジェクト (各画像は hachie::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

もっと簡単な方法はありますか?

画像は hachie::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

解決策

あなたはハッシュ#スライスを求めています:

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

これにより、返されたハッシュに含めるキーを「ホワイトリスト」に登録できます。拒否する値よりも承認する値の方が多い場合は、その逆を行い、Hash#excel を使用して拒否するキーのみをリストすることができます。

どちらの場合でも、許可されるキーのリストを別の配列として保存し、それを * で分割する方が簡単かもしれません。

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