2016-04-27 1 views
0

私はこのメソッドは、各ハリー::マッシュオブジェクトから特定のフィールドを選択しようとします(それぞれのイメージはハリー::マッシュオブジェクトです)。ハッシュで特定のキーのみを拒否または許可するにはどうすればよいですか?

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 ::マッシュオブジェクトの配列です。

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元のコードには、完全なRailsアプリケーションである[Spree](https://github.com/spree/spree)への参照があります。 – tadman

関連する問題