mardi 15 mars 2016

How to optimize this ActiveModel Serializer? Rails 3

I have this code right now:

module Api
  module V20150315
    class RecipeToolSerializer < ActiveModel::Serializer
      cached
      delegate :cache_key, to: :object

      attributes :id,
                 :display_name,
                 :images,
                 :display_price,
                 :description,
                 :main_image,
                 :subtitle

      def display_name
        object.display_name
      end

      def images
        object.story.get_spree_product.master.images
      end

      def display_price
        object.story.get_spree_product.master.display_price
      end

      def description
        object.story.description
      end

      def main_image
        object.story.main_image
      end

      def subtitle
        object.story.get_spree_product.subtitle
      end

      def spree_product
        spree_product.nil? ? nil : spree_product.to_hash
      end

      private

      def recipe_tool_spree_product
        @spree_product ||= object.story.get_spree_product
      end
    end
  end
end

Here are some issues I have with it:

  1. It doesn't cache object.story (this will trigger a SQL query)
  2. It doens't cache object.story.get_spree_product (this will make an API call)
  3. Is it currently caching on the object's id and updated time by default?

Aucun commentaire:

Enregistrer un commentaire