Skip to content

Instantly share code, notes, and snippets.

@jess
Created September 24, 2015 18:49

Revisions

  1. jess created this gist Sep 24, 2015.
    64 changes: 64 additions & 0 deletions product_decorator.rb
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,64 @@
    Spree::Product::ElasticsearchQuery.class_eval do
    def query_fields
    ['_all']
    end
    end

    Spree::Product.class_eval do
    has_many :model_numbers, class: Spree::ModelNumber, foreign_key: "spree_product_id", dependent: :destroy
    has_many :vendors, class: Spree::Vendor, through: :model_numbers
    has_many :tags, class: Spree::ProductTag, foreign_key: "spree_product_id", dependent: :destroy

    include Elasticsearch::Model::Callbacks

    def old_url=(old_url)
    return if old_url.blank?
    url = URI.parse(old_url)

    product_id = Rack::Utils.parse_nested_query(url.query)["productid"]
    if product_id
    Spree::Redirect.create!(old_url: url.path, new_url: "/store/products/#{slug}", productid: product_id)
    else
    Spree::Redirect.create!(old_url: url.path, new_url: "/store/products/#{slug}")
    end
    page = Nokogiri::HTML(open(old_url))
    self.description ||= page.css('form[name="orderform"] table')[1].css('tr')[0].css('td')[0].text.strip
    end

    def old_image_url=(old_url)
    return if old_url.nil?
    Spree::Redirect.create!(old_url: URI(old_url).path, new_url: self.images.last.attachment.url(:original))
    puts "Successfully created Redirect for #{old_url}"
    end

    # Overriding ElasticSearch to add attributes
    def as_indexed_json(options={})
    result = as_json({
    methods: [:price, :sku],
    only: [:available_on, :description, :name],
    include: {
    variants: {
    only: [:sku],
    include: {
    option_values: {
    only: [:name, :presentation]
    }
    }
    },
    product_properties: {
    methods: [:property_name],
    only: [:value]
    },
    model_numbers: {
    only: [:number],
    methods: [:vendor_name]
    }
    }
    })
    result[:properties] = property_list unless property_list.empty?
    result[:taxon_ids] = taxons.map(&:self_and_ancestors).flatten.uniq.map(&:id) unless taxons.empty?
    result[:tags] = tags.collect(&:tag)
    result
    end

    end