repo
stringlengths
5
92
file_url
stringlengths
80
287
file_path
stringlengths
5
197
content
stringlengths
0
32.8k
language
stringclasses
1 value
license
stringclasses
7 values
commit_sha
stringlengths
40
40
retrieved_at
stringdate
2026-01-04 15:37:27
2026-01-04 17:58:21
truncated
bool
2 classes
Shopify/product-taxonomy
https://github.com/Shopify/product-taxonomy/blob/a1cb6132c9c0885c88ecbda53777f1dfc0e064d9/dev/lib/product_taxonomy/commands/dump_values_command.rb
dev/lib/product_taxonomy/commands/dump_values_command.rb
# frozen_string_literal: true module ProductTaxonomy class DumpValuesCommand < Command def execute logger.info("Dumping values...") load_taxonomy path = File.expand_path("values.yml", ProductTaxonomy.data_path) FileUtils.mkdir_p(File.dirname(path)) data = Serializers::Value::Data::DataSerializer.serialize_all File.write(path, YAML.dump(data, line_width: -1)) logger.info("Updated `#{path}`") end end end
ruby
MIT
a1cb6132c9c0885c88ecbda53777f1dfc0e064d9
2026-01-04T17:02:35.318003Z
false
Shopify/product-taxonomy
https://github.com/Shopify/product-taxonomy/blob/a1cb6132c9c0885c88ecbda53777f1dfc0e064d9/dev/lib/product_taxonomy/commands/find_unmapped_external_categories_command.rb
dev/lib/product_taxonomy/commands/find_unmapped_external_categories_command.rb
# frozen_string_literal: true module ProductTaxonomy class FindUnmappedExternalCategoriesCommand < Command def execute(name_and_version) load_taxonomy # not actually used in this operation, but required by IntegrationVersion to resolve categories unless name_and_version.match?(%r{\A[a-z0-9_-]+/[^/]+\z}) raise ArgumentError, "Invalid format. Expected 'name/version', got: #{name_and_version}" end # Load relevant IntegrationVersion using CLI argument integration_path = File.join(IntegrationVersion::INTEGRATIONS_PATH, name_and_version) integration_version = IntegrationVersion.load_from_source(integration_path:) # Output the unmapped external categories integration_version.unmapped_external_category_ids.each do |id| puts integration_version.full_names_by_id[id]["full_name"] end end end end
ruby
MIT
a1cb6132c9c0885c88ecbda53777f1dfc0e064d9
2026-01-04T17:02:35.318003Z
false
Shopify/product-taxonomy
https://github.com/Shopify/product-taxonomy/blob/a1cb6132c9c0885c88ecbda53777f1dfc0e064d9/dev/lib/product_taxonomy/commands/add_category_command.rb
dev/lib/product_taxonomy/commands/add_category_command.rb
# frozen_string_literal: true module ProductTaxonomy class AddCategoryCommand < Command def initialize(options) super load_taxonomy @name = options[:name] @parent_id = options[:parent_id] @id = options[:id] end def execute create_category! update_data_files! end private def create_category! parent = Category.find_by!(id: @parent_id) @new_category = Category.new(id: @id || parent.next_child_id, name: @name, parent:) begin @new_category.validate!(:create) rescue ActiveModel::ValidationError => e raise ActiveModel::ValidationError.new(e.model), "Failed to create category: #{e.message}" end parent.add_child(@new_category) Category.add(@new_category) logger.info("Created category `#{@new_category.name}` with id=`#{@new_category.id}`") end def update_data_files! DumpCategoriesCommand.new(verticals: [@new_category.root.id]).execute SyncEnLocalizationsCommand.new(targets: "categories").execute GenerateDocsCommand.new({}).execute end end end
ruby
MIT
a1cb6132c9c0885c88ecbda53777f1dfc0e064d9
2026-01-04T17:02:35.318003Z
false
Shopify/product-taxonomy
https://github.com/Shopify/product-taxonomy/blob/a1cb6132c9c0885c88ecbda53777f1dfc0e064d9/dev/lib/product_taxonomy/commands/dump_attributes_command.rb
dev/lib/product_taxonomy/commands/dump_attributes_command.rb
# frozen_string_literal: true module ProductTaxonomy class DumpAttributesCommand < Command def execute logger.info("Dumping attributes...") load_taxonomy path = File.expand_path("attributes.yml", ProductTaxonomy.data_path) FileUtils.mkdir_p(File.dirname(path)) data = Serializers::Attribute::Data::DataSerializer.serialize_all File.write(path, YAML.dump(data, line_width: -1)) logger.info("Updated `#{path}`") end end end
ruby
MIT
a1cb6132c9c0885c88ecbda53777f1dfc0e064d9
2026-01-04T17:02:35.318003Z
false
Shopify/product-taxonomy
https://github.com/Shopify/product-taxonomy/blob/a1cb6132c9c0885c88ecbda53777f1dfc0e064d9/dev/lib/product_taxonomy/models/value.rb
dev/lib/product_taxonomy/models/value.rb
# frozen_string_literal: true module ProductTaxonomy # An attribute value in the product taxonomy. Referenced by a {ProductTaxonomy::Attribute}. For example, an # attribute called "Color" could have values "Red", "Blue", and "Green". class Value include ActiveModel::Validations include FormattedValidationErrors extend Localized extend Indexed class << self # Load values from source data. By default, this data is deserialized from a YAML file in the `data` directory. # # @param source_data [Array<Hash>] The source data to load values from. def load_from_source(source_data) raise ArgumentError, "source_data must be an array" unless source_data.is_a?(Array) source_data.each do |value_data| raise ArgumentError, "source_data must contain hashes" unless value_data.is_a?(Hash) Value.create_validate_and_add!( id: value_data["id"], name: value_data["name"], friendly_id: value_data["friendly_id"], handle: value_data["handle"], ) end end # Reset all class-level state def reset @localizations = nil @hashed_models = nil end # Sort values by their localized name. # # @param values [Array<Value>] The values to sort. # @param locale [String] The locale to sort by. # @return [Array<Value>] The sorted values. def sort_by_localized_name(values, locale: "en") values.sort_by.with_index do |value, idx| [ value.name(locale: "en").downcase == "other" ? 1 : 0, *AlphanumericSorter.normalize_value(value.name(locale:)), idx, ] end end # Sort values according to their English name, taking "other" into account. # # @param values [Array<Value>] The values to sort. # @return [Array<Value>] The sorted values. def all_values_sorted all.sort_by do |value| [ value.name(locale: "en").downcase == "other" ? 1 : 0, value.name(locale: "en"), value.id, ] end end # Get the next ID for a newly created value. # # @return [Integer] The next ID. def next_id = (all.max_by(&:id)&.id || 0) + 1 end # Validations that run when the value is created validates :id, presence: true, numericality: { only_integer: true }, on: :create validates :name, presence: true, on: :create validates :friendly_id, presence: true, on: :create validates :handle, presence: true, on: :create validates_with ProductTaxonomy::Indexed::UniquenessValidator, attributes: [:friendly_id, :handle, :id], on: :create # Validations that run when the taxonomy has been loaded validate :friendly_id_prefix_resolves_to_attribute?, on: :taxonomy_loaded validate :handle_prefix_matches_attribute?, on: :taxonomy_loaded localized_attr_reader :name attr_reader :id, :friendly_id, :handle # @param id [Integer] The ID of the value. # @param name [String] The name of the value. # @param friendly_id [String] The friendly ID of the value. # @param handle [String] The handle of the value. def initialize(id:, name:, friendly_id:, handle:) @id = id @name = name @friendly_id = friendly_id @handle = handle end def gid "gid://shopify/TaxonomyValue/#{id}" end # Get the primary attribute for this value. # # @return [ProductTaxonomy::Attribute] The primary attribute for this value. def primary_attribute @primary_attribute ||= Attribute.find_by(friendly_id: primary_attribute_friendly_id) end # Get the full name of the value, including the primary attribute. # # @param locale [String] The locale to get the name in. # @return [String] The full name of the value. def full_name(locale: "en") "#{name(locale:)} [#{primary_attribute.name(locale:)}]" end private def primary_attribute_friendly_id = friendly_id.split("__").first # # Validation # def friendly_id_prefix_resolves_to_attribute? return if primary_attribute errors.add( :friendly_id, :invalid_prefix, message: "prefix \"#{primary_attribute_friendly_id}\" does not match the friendly_id of any attribute", ) end def handle_prefix_matches_attribute? return if primary_attribute.nil? handle_prefix = handle.split("__").first return if primary_attribute && primary_attribute.handle == handle_prefix errors.add( :handle, :invalid_prefix, message: "prefix \"#{handle_prefix}\" does not match primary attribute handle \"#{primary_attribute.handle}\"", ) end end end
ruby
MIT
a1cb6132c9c0885c88ecbda53777f1dfc0e064d9
2026-01-04T17:02:35.318003Z
false
Shopify/product-taxonomy
https://github.com/Shopify/product-taxonomy/blob/a1cb6132c9c0885c88ecbda53777f1dfc0e064d9/dev/lib/product_taxonomy/models/taxonomy.rb
dev/lib/product_taxonomy/models/taxonomy.rb
# frozen_string_literal: true module ProductTaxonomy class Taxonomy attr_reader :verticals def initialize(verticals:) @verticals = verticals end end end
ruby
MIT
a1cb6132c9c0885c88ecbda53777f1dfc0e064d9
2026-01-04T17:02:35.318003Z
false
Shopify/product-taxonomy
https://github.com/Shopify/product-taxonomy/blob/a1cb6132c9c0885c88ecbda53777f1dfc0e064d9/dev/lib/product_taxonomy/models/attribute.rb
dev/lib/product_taxonomy/models/attribute.rb
# frozen_string_literal: true module ProductTaxonomy class Attribute include ActiveModel::Validations include FormattedValidationErrors extend Localized extend Indexed class << self # Load attributes from source data. By default, this data is deserialized from a YAML file in the `data` directory. # # @param source_data [Array<Hash>] The source data to load attributes from. def load_from_source(source_data) raise ArgumentError, "source_data must be a hash" unless source_data.is_a?(Hash) raise ArgumentError, "source_data must contain keys \"base_attributes\" and \"extended_attributes\"" unless source_data.keys.sort == ["base_attributes", "extended_attributes"] source_data.each do |type, attributes| attributes.each do |attribute_data| raise ArgumentError, "source_data must contain hashes" unless attribute_data.is_a?(Hash) attribute = case type when "base_attributes" then attribute_from(attribute_data) when "extended_attributes" then extended_attribute_from(attribute_data) end Attribute.add(attribute) attribute.validate!(:create) end end end # Reset all class-level state def reset @localizations = nil @hashed_models = nil end # Get base attributes only, sorted by name. # # @return [Array<Attribute>] The sorted base attributes. def sorted_base_attributes all.reject(&:extended?).sort_by(&:name) end # Get the next ID for a newly created attribute. # # @return [Integer] The next ID. def next_id = (all.max_by(&:id)&.id || 0) + 1 private def attribute_from(attribute_data) values_by_friendly_id = attribute_data["values"]&.map { Value.find_by(friendly_id: _1) || _1 } Attribute.new( id: attribute_data["id"], name: attribute_data["name"], description: attribute_data["description"], friendly_id: attribute_data["friendly_id"], handle: attribute_data["handle"], values: values_by_friendly_id, is_manually_sorted: attribute_data["sorting"] == "custom", ) end def extended_attribute_from(attribute_data) value_friendly_id = attribute_data["values_from"] ExtendedAttribute.new( name: attribute_data["name"], handle: attribute_data["handle"], description: attribute_data["description"], friendly_id: attribute_data["friendly_id"], values_from: Attribute.find_by(friendly_id: value_friendly_id) || value_friendly_id, ) end end validates :id, presence: true, numericality: { only_integer: true }, if: -> { self.class == Attribute }, on: :create validates :name, presence: true, on: :create validates :friendly_id, presence: true, on: :create validates :handle, presence: true, on: :create validates :description, presence: true, on: :create validates :values, presence: true, if: -> { self.class == Attribute }, on: :create validates_with ProductTaxonomy::Indexed::UniquenessValidator, attributes: [:friendly_id], on: :create validate :values_valid?, on: :create localized_attr_reader :name, :description attr_reader :id, :friendly_id, :handle, :values, :extended_attributes # @param id [Integer] The ID of the attribute. # @param name [String] The name of the attribute. # @param description [String] The description of the attribute. # @param friendly_id [String] The friendly ID of the attribute. # @param handle [String] The handle of the attribute. # @param values [Array<Value, String>] An array of resolved {Value} objects. When resolving fails, use the friendly # ID instead. def initialize(id:, name:, description:, friendly_id:, handle:, values:, is_manually_sorted: false) @id = id @name = name @description = description @friendly_id = friendly_id @handle = handle @values = values @extended_attributes = [] @is_manually_sorted = is_manually_sorted end # Add an extended attribute to the attribute. # # @param extended_attribute [ExtendedAttribute] The extended attribute to add. def add_extended_attribute(extended_attribute) @extended_attributes << extended_attribute end # Add a value to the attribute. # # @param value [Value] The value to add. def add_value(value) @values << value end # The global ID of the attribute # # @return [String] def gid "gid://shopify/TaxonomyAttribute/#{id}" end # Whether the attribute is an extended attribute. # # @return [Boolean] def extended? is_a?(ExtendedAttribute) end # Whether the attribute is manually sorted. # # @return [Boolean] def manually_sorted? @is_manually_sorted end # Get the sorted values of the attribute. # # @param locale [String] The locale to sort by. # @return [Array<Value>] The sorted values. def sorted_values(locale: "en") if manually_sorted? values else Value.sort_by_localized_name(values, locale:) end end private def values_valid? values&.each do |value| next if value.is_a?(Value) errors.add( :values, :not_found, message: "not found for friendly ID \"#{value}\"", ) end end end end
ruby
MIT
a1cb6132c9c0885c88ecbda53777f1dfc0e064d9
2026-01-04T17:02:35.318003Z
false
Shopify/product-taxonomy
https://github.com/Shopify/product-taxonomy/blob/a1cb6132c9c0885c88ecbda53777f1dfc0e064d9/dev/lib/product_taxonomy/models/category.rb
dev/lib/product_taxonomy/models/category.rb
# frozen_string_literal: true module ProductTaxonomy class Category include ActiveModel::Validations include FormattedValidationErrors extend Localized extend Indexed class << self attr_reader :verticals # Load categories from source data. # # @param source_data [Array<Hash>] The source data to load categories from. def load_from_source(source_data) raise ArgumentError, "source_data must be an array" unless source_data.is_a?(Array) # First pass: Create all nodes and add to index source_data.each do |item| Category.create_validate_and_add!( id: item["id"], name: item["name"], attributes: Array(item["attributes"]).map { Attribute.find_by(friendly_id: _1) || _1 }, ) end # Second pass: Build relationships source_data.each do |item| parent = Category.find_by(id: item["id"]) add_children(type: "children", item:, parent:) add_children(type: "secondary_children", item:, parent:) end # Third pass: Validate all nodes, sort contents, and collect root nodes for verticals @verticals = Category.all.each_with_object([]) do |node, root_nodes| node.validate!(:category_tree_loaded) node.children.sort_by!(&:name) node.attributes.sort_by!(&:name) root_nodes << node if node.root? end @verticals.sort_by!(&:name) end # Reset all class-level state def reset @localizations = nil @hashed_models = nil @verticals = nil end # Get all categories in depth-first order. # # @return [Array<Category>] The categories in depth-first order. def all_depth_first verticals.flat_map(&:descendants_and_self) end private def add_children(type:, item:, parent:) item[type]&.each do |child_id| child = Category.find_by(id: child_id) || child_id case type when "children" then parent.add_child(child) when "secondary_children" then parent.add_secondary_child(child) end end end end # Validations that can be performed as soon as the category is created. validates :id, format: { with: /\A[a-z]{2}(-\d+)*\z/ }, on: :create validates :name, presence: true, on: :create validate :attributes_found?, on: :create validates_with ProductTaxonomy::Indexed::UniquenessValidator, attributes: [:id], on: :create # Validations that can only be performed after the category tree has been loaded. validate :id_matches_depth, on: :category_tree_loaded validate :id_starts_with_parent_id, unless: :root?, on: :category_tree_loaded validate :children_found?, on: :category_tree_loaded validate :secondary_children_found?, on: :category_tree_loaded localized_attr_reader :name, keyed_by: :id attr_reader :id, :children, :secondary_children, :attributes attr_accessor :parent, :secondary_parents # @param id [String] The ID of the category. # @param name [String] The name of the category. # @param attributes [Array<Attribute>] The attributes of the category. # @param parent [Category] The parent category of the category. def initialize(id:, name:, attributes: [], parent: nil) @id = id @name = name @children = [] @secondary_children = [] @attributes = attributes @parent = parent @secondary_parents = [] end # # Manipulation # # Add a child to the category # # @param [Category|String] child node, or the friendly ID if the node was not found. def add_child(child) @children << child return unless child.is_a?(Category) child.parent = self end # Add a secondary child to the category # # @param [Category|String] child node, or the friendly ID if the node was not found. def add_secondary_child(child) @secondary_children << child return unless child.is_a?(Category) child.secondary_parents << self end # Add an attribute to the category # # @param [Attribute] attribute def add_attribute(attribute) @attributes << attribute end # # Information # def inspect "#<#{self.class.name} id=#{id} name=#{name}>" end # Whether the category is the root category # # @return [Boolean] def root? parent.nil? end # Whether the category is a leaf category # # @return [Boolean] def leaf? children.empty? end # The level of the category # # @return [Integer] def level ancestors.size end # The root category in this category's tree # # @return [Category] def root ancestors.last || self end # The ancestors of the category # # @return [Array<Category>] def ancestors return [] if root? [parent] + parent.ancestors end # The full name of the category # # @return [String] def full_name(locale: "en") return name(locale:) if root? parent.full_name(locale:) + " > " + name(locale:) end # The global ID of the category # # @return [String] def gid "gid://shopify/TaxonomyCategory/#{id}" end # Split an ID into its parts. # # @return [Array<String, Integer>] The parts of the ID. def id_parts parts = id.split("-") [parts.first] + parts[1..].map(&:to_i) end # Whether the category is a descendant of another category # # @param [Category] category # @return [Boolean] def descendant_of?(category) ancestors.include?(category) end # Iterate over the category and all its descendants # # @yield [Category] def traverse(&block) yield self children.each { _1.traverse(&block) } end # The descendants of the category def descendants children.flat_map { |child| [child] + child.descendants } end # The descendants of the category and the category itself # # @return [Array<Category>] def descendants_and_self [self] + descendants end # The friendly name of the category # # @return [String] def friendly_name "#{id}_#{IdentifierFormatter.format_friendly_id(name)}" end # The next child ID for the category # # @return [String] def next_child_id largest_child_id = children.map { _1.id.split("-").last.to_i }.max || 0 "#{id}-#{largest_child_id + 1}" end private # # Validation # def id_matches_depth parts_count = id.split("-").size return if parts_count == level + 1 if level.zero? # In this case, the most likely mistake was not adding the category to the parent's `children` field. errors.add(:base, :orphan, message: "\"#{id}\" does not appear in the children of any category") else errors.add( :id, :depth_mismatch, message: "\"#{id}\" has #{parts_count} #{"part".pluralize(parts_count)} but is at level #{level + 1}", ) end end def id_starts_with_parent_id return if id.start_with?(parent.id) errors.add(:id, :prefix_mismatch, message: "\"#{id}\" must be prefixed by \"#{parent.id}\"") end def attributes_found? attributes&.each do |attribute| next if attribute.is_a?(Attribute) errors.add( :attributes, :not_found, message: "not found for friendly ID \"#{attribute}\"", ) end end def children_found? children&.each do |child| next if child.is_a?(Category) errors.add( :children, :not_found, message: "not found for friendly ID \"#{child}\"", ) end end def secondary_children_found? secondary_children&.each do |child| next if child.is_a?(Category) errors.add( :secondary_children, :not_found, message: "not found for friendly ID \"#{child}\"", ) end end end end
ruby
MIT
a1cb6132c9c0885c88ecbda53777f1dfc0e064d9
2026-01-04T17:02:35.318003Z
false
Shopify/product-taxonomy
https://github.com/Shopify/product-taxonomy/blob/a1cb6132c9c0885c88ecbda53777f1dfc0e064d9/dev/lib/product_taxonomy/models/extended_attribute.rb
dev/lib/product_taxonomy/models/extended_attribute.rb
# frozen_string_literal: true module ProductTaxonomy class ExtendedAttribute < Attribute class << self def localizations superclass.localizations # Extended attribute localizations are defined in the same place as attributes end end validate :values_from_valid? attr_reader :values_from alias_method :base_attribute, :values_from # @param name [String] The name of the attribute. # @param handle [String] The handle of the attribute. # @param description [String] The description of the attribute. # @param friendly_id [String] The friendly ID of the attribute. # @param values_from [Attribute, String] A resolved {Attribute} object. When resolving fails, pass the friendly ID # instead. def initialize(name:, handle:, description:, friendly_id:, values_from:) @values_from = values_from values_from.add_extended_attribute(self) if values_from.is_a?(Attribute) super( id: values_from.try(:id), name:, handle:, description:, friendly_id:, values: values_from.try(:values), is_manually_sorted: values_from.try(:manually_sorted?) || false, ) end private def values_from_valid? errors.add( :base_attribute, :not_found, message: "not found for friendly ID \"#{values_from}\"", ) unless values_from.is_a?(Attribute) end end end
ruby
MIT
a1cb6132c9c0885c88ecbda53777f1dfc0e064d9
2026-01-04T17:02:35.318003Z
false
Shopify/product-taxonomy
https://github.com/Shopify/product-taxonomy/blob/a1cb6132c9c0885c88ecbda53777f1dfc0e064d9/dev/lib/product_taxonomy/models/mapping_rule.rb
dev/lib/product_taxonomy/models/mapping_rule.rb
# frozen_string_literal: true module ProductTaxonomy # A mapping rule for converting between the integration's taxonomy and Shopify's taxonomy. class MappingRule class << self # Load mapping rules from the provided source data directory for a single direction. # # @param integration_path [String] The path to the integration version source data directory. # @param direction [Symbol] The direction of the mapping rules to load (:from_shopify or :to_shopify). # @param full_names_by_id [Hash<String, Hash>] A hash of full names by ID. # @return [Array<MappingRule>, nil] def load_rules_from_source(integration_path:, direction:, full_names_by_id:) file_path = File.expand_path("mappings/#{direction}.yml", integration_path) return unless File.exist?(file_path) data = YAML.safe_load_file(file_path) raise ArgumentError, "Mapping rules file does not contain a hash: #{file_path}" unless data.is_a?(Hash) raise ArgumentError, "Mapping rules file does not have a `rules` key: #{file_path}" unless data.key?("rules") unless data["rules"].is_a?(Array) raise ArgumentError, "Mapping rules file `rules` value is not an array: #{file_path}" end data["rules"].map do |rule| input_id = rule.dig("input", "product_category_id")&.to_s output_id = rule.dig("output", "product_category_id")&.first&.to_s raise ArgumentError, "Invalid mapping rule: #{rule}" if input_id.nil? || output_id.nil? is_to_shopify = direction == :to_shopify input_category = is_to_shopify ? full_names_by_id[input_id] : Category.find_by(id: input_id) # We set output_category to be the raw output ID if is_to_shopify is true, with an expectation that it will # be resolved to a `Category` before the rule is serialized to JSON or TXT. # See `IntegrationVersion#resolve_to_shopify_mappings`. output_category = is_to_shopify ? output_id : full_names_by_id[output_id] raise ArgumentError, "Input category not found for mapping rule: #{rule}" unless input_category raise ArgumentError, "Output category not found for mapping rule: #{rule}" unless output_category new(input_category:, output_category:) rescue TypeError, NoMethodError raise ArgumentError, "Invalid mapping rule: #{rule}" end end end attr_reader :input_category attr_accessor :output_category def initialize(input_category:, output_category:) @input_category = input_category @output_category = output_category end # Generate a JSON representation of the mapping rule. # # @return [Hash] def to_json { input: { category: category_json(@input_category), }, output: { category: [category_json(@output_category)], }, } end # Generate a TXT representation of the mapping rule. # # @return [String] def to_txt <<~TXT → #{category_txt(@input_category)} ⇒ #{category_txt(@output_category)} TXT end # Whether the input and output categories have the same full name. # # @return [Boolean] def input_txt_equals_output_txt? category_txt(@input_category) == category_txt(@output_category) end private def category_json(category) if category.is_a?(Hash) { id: category["id"].to_s, full_name: category["full_name"], } elsif category.is_a?(Category) { id: category.gid, full_name: category.full_name, } else raise ArgumentError, "Mapping rule category not resolved. Raw value: #{category}" end end def category_txt(category) if category.is_a?(Hash) category["full_name"] elsif category.is_a?(Category) category.full_name else raise ArgumentError, "Mapping rule category not resolved. Raw value: #{category}" end end end end
ruby
MIT
a1cb6132c9c0885c88ecbda53777f1dfc0e064d9
2026-01-04T17:02:35.318003Z
false
Shopify/product-taxonomy
https://github.com/Shopify/product-taxonomy/blob/a1cb6132c9c0885c88ecbda53777f1dfc0e064d9/dev/lib/product_taxonomy/models/integration_version.rb
dev/lib/product_taxonomy/models/integration_version.rb
# frozen_string_literal: true module ProductTaxonomy # A single version of an integration, e.g. "shopify/2024-07". # # Includes: # - The full names of categories in the integration's taxonomy. # - The mapping rules for converting between the integration's taxonomy and Shopify's taxonomy. class IntegrationVersion INTEGRATIONS_PATH = File.expand_path("integrations", ProductTaxonomy.data_path) class << self # Generate all distribution files for all integration versions. # # @param output_path [String] The path to the output directory. # @param logger [Logger] The logger to use for logging messages. # @param current_shopify_version [String] The current version of the Shopify taxonomy. # @param base_path [String] The path to the base directory containing integration versions. def generate_all_distributions(output_path:, logger:, current_shopify_version: nil, base_path: INTEGRATIONS_PATH) clear_shopify_integrations_directory(output_path:, logger:) integration_versions = load_all_from_source(current_shopify_version:, base_path:) all_mappings = integration_versions.each_with_object([]) do |integration_version, all_mappings| logger.info("Generating integration mappings for #{integration_version.name}/#{integration_version.version}") integration_version.generate_distributions(output_path:) all_mappings.concat(integration_version.to_json(direction: :both)) end generate_all_mappings_file(mappings: all_mappings, current_shopify_version:, output_path:) end # Clear the Shopify integrations directory before generating new files. # # @param output_path [String] The path to the output directory. # @param logger [Logger] The logger to use for logging messages. def clear_shopify_integrations_directory(output_path:, logger:) shopify_integrations_path = File.join(integrations_output_path(output_path), "shopify") if Dir.exist?(shopify_integrations_path) FileUtils.rm_rf(shopify_integrations_path) FileUtils.mkdir_p(shopify_integrations_path) end end # Load all integration versions from the source data directory. # # @return [Array<IntegrationVersion>] def load_all_from_source(current_shopify_version: nil, base_path: INTEGRATIONS_PATH) integrations_yaml = YAML.safe_load_file(File.expand_path("integrations.yml", base_path)) integrations_yaml.flat_map do |integration_yaml| versions = integration_yaml["available_versions"].sort.map do |version_path| load_from_source( integration_path: File.expand_path(version_path, base_path), current_shopify_version:, ) end resolve_to_shopify_mappings_chain(versions) if integration_yaml["name"] == "shopify" versions end end # Resolve a set of IntegrationVersion to_shopify mappings so that each one maps to the latest version of the # Shopify taxonomy. # # @param versions [Array<IntegrationVersion>] The versions to resolve, ordered from oldest to newest. def resolve_to_shopify_mappings_chain(versions) versions.reverse.each_with_object([]) do |version, resolved_versions| version.resolve_to_shopify_mappings(resolved_versions) resolved_versions.prepend(version) end end # Load an integration version from the provided source data directory. # # @param integration_path [String] The path to the integration version source data directory. # @return [IntegrationVersion] def load_from_source(integration_path:, current_shopify_version: nil) full_names = YAML.safe_load_file(File.expand_path("full_names.yml", integration_path)) full_names_by_id = full_names.each_with_object({}) { |data, hash| hash[data["id"].to_s] = data } from_shopify_mappings = MappingRule.load_rules_from_source( integration_path:, direction: :from_shopify, full_names_by_id:, ) to_shopify_mappings = MappingRule.load_rules_from_source( integration_path:, direction: :to_shopify, full_names_by_id:, ) integration_pathname = Pathname.new(integration_path) new( name: integration_pathname.parent.basename.to_s, version: integration_pathname.basename.to_s, full_names_by_id:, from_shopify_mappings:, to_shopify_mappings:, current_shopify_version:, ) end # Generate a JSON file containing all mappings for all integration versions. # # @param mappings [Array<Hash>] The mappings to include in the file. # @param version [String] The current version of the Shopify taxonomy. # @param output_path [String] The path to the output directory. def generate_all_mappings_file(mappings:, current_shopify_version:, output_path:) File.write( File.expand_path("all_mappings.json", integrations_output_path(output_path)), JSON.pretty_generate(to_json(mappings:, current_shopify_version:)) + "\n", ) end # Generate a JSON representation for a given set of mappings and version of the Shopify taxonomy. # # @param version [String] The current version of the Shopify taxonomy. # @param mappings [Array<Hash>] The mappings to include in the file. # @return [Hash] def to_json(current_shopify_version:, mappings:) { version: current_shopify_version, mappings:, } end # Generate the path to the integrations output directory. # # @param base_output_path [String] The base path to the output directory. # @return [String] def integrations_output_path(base_output_path) File.expand_path("en/integrations", base_output_path) end end attr_reader :name, :version, :from_shopify_mappings, :to_shopify_mappings, :full_names_by_id # @param name [String] The name of the integration. # @param version [String] The version of the integration. # @param full_names_by_id [Hash<String, Hash>] A hash of full names by ID. # @param current_shopify_version [String] The current version of the Shopify taxonomy. # @param from_shopify_mappings [Array<MappingRule>] The mappings from the Shopify taxonomy to the integration's # taxonomy. # @param to_shopify_mappings [Array<MappingRule>] The mappings from the integration's taxonomy to the Shopify # taxonomy. def initialize( name:, version:, full_names_by_id:, current_shopify_version: nil, from_shopify_mappings: nil, to_shopify_mappings: nil ) @name = name @version = version @full_names_by_id = full_names_by_id @current_shopify_version = current_shopify_version @from_shopify_mappings = from_shopify_mappings @to_shopify_mappings = to_shopify_mappings @to_json = {} # memoized by direction end # Generate all distribution files for the integration version. # # @param output_path [String] The path to the output directory. def generate_distributions(output_path:) generate_distribution(output_path:, direction: :from_shopify) if @from_shopify_mappings.present? generate_distribution(output_path:, direction: :to_shopify) if @to_shopify_mappings.present? end # Generate JSON and TXT distribution files for a single direction of the integration version. # # @param output_path [String] The path to the output directory. # @param direction [Symbol] The direction of the distribution file to generate (:from_shopify or :to_shopify). def generate_distribution(output_path:, direction:) output_dir = File.expand_path(@name, self.class.integrations_output_path(output_path)) FileUtils.mkdir_p(output_dir) json = self.class.to_json(mappings: [to_json(direction:)], current_shopify_version: @current_shopify_version) File.write( File.expand_path("#{distribution_filename(direction:)}.json", output_dir), JSON.pretty_generate(json) + "\n", ) File.write( File.expand_path("#{distribution_filename(direction:)}.txt", output_dir), to_txt(direction:) + "\n", ) end # Resolve the output categories of to_shopify mappings to the current version of the Shopify taxonomy, taking into # any mappings from later versions. # # @param next_integration_versions [Array<IntegrationVersion>] An array of Shopify integration versions coming # after the current version. def resolve_to_shopify_mappings(next_integration_versions) @to_shopify_mappings&.each do |mapping| newer_mapping = next_integration_versions.flat_map(&:to_shopify_mappings).compact.find do |mapping_rule| mapping_rule.input_category["id"] == mapping.output_category end mapping.output_category = newer_mapping&.output_category || Category.find_by(id: mapping.output_category) next unless mapping.output_category.nil? raise ArgumentError, "Failed to resolve Shopify mapping: " \ "\"#{mapping.input_category["id"]}\" to \"#{mapping.output_category}\" " \ "(input version: #{version})" end end # For a mapping to an external taxonomy, get the IDs of external categories that are not mapped from Shopify. # # @return [Array<String>] IDs of external categories not mapped from the Shopify taxonomy. Empty if there are no # mappings from Shopify. def unmapped_external_category_ids return [] if @from_shopify_mappings.blank? mappings_by_output_category_id = @from_shopify_mappings.index_by { _1.output_category["id"].to_s } @full_names_by_id.keys - mappings_by_output_category_id.keys end # Generate a JSON representation of the integration version for a single direction. # # @param direction [Symbol] The direction of the distribution file to generate (:from_shopify or :to_shopify). # @return [Hash, Array<Hash>, nil] def to_json(direction:) if @to_json.key?(direction) @to_json[direction] elsif direction == :both [to_json(direction: :from_shopify), to_json(direction: :to_shopify)].compact else mappings = if direction == :from_shopify @from_shopify_mappings&.sort_by { _1.input_category.id_parts } else @to_shopify_mappings end @to_json[direction] = if mappings.present? { input_taxonomy: input_name_and_version(direction:), output_taxonomy: output_name_and_version(direction:), rules: mappings.map(&:to_json), } end end end # Generate a TXT representation of the integration version for a single direction. # # @param direction [Symbol] The direction of the distribution file to generate (:from_shopify or :to_shopify). # @return [String] def to_txt(direction:) mappings = direction == :from_shopify ? @from_shopify_mappings : @to_shopify_mappings header = <<~TXT # Shopify Product Taxonomy - Mapping #{input_name_and_version(direction:)} to #{output_name_and_version(direction:)} # Format: # → {base taxonomy category name} # ⇒ {mapped taxonomy category name} TXT visible_mappings = mappings.filter_map do |mapping| next if @name == "shopify" && direction == :to_shopify && mapping.input_txt_equals_output_txt? mapping.to_txt end header + visible_mappings.sort.join("\n").chomp end private def distribution_filename(direction:) "#{input_name_and_version(direction:)}_to_#{output_name_and_version(direction:)}" .gsub("/", "_") .gsub("-unstable", "") end def integration_name_and_version "#{@name}/#{@version}" end def shopify_name_and_version "shopify/#{@current_shopify_version}" end def input_name_and_version(direction:) direction == :from_shopify ? shopify_name_and_version : integration_name_and_version end def output_name_and_version(direction:) direction == :from_shopify ? integration_name_and_version : shopify_name_and_version end end end
ruby
MIT
a1cb6132c9c0885c88ecbda53777f1dfc0e064d9
2026-01-04T17:02:35.318003Z
false
Shopify/product-taxonomy
https://github.com/Shopify/product-taxonomy/blob/a1cb6132c9c0885c88ecbda53777f1dfc0e064d9/dev/lib/product_taxonomy/models/serializers/category/docs/siblings_serializer.rb
dev/lib/product_taxonomy/models/serializers/category/docs/siblings_serializer.rb
# frozen_string_literal: true module ProductTaxonomy module Serializers module Category module Docs module SiblingsSerializer class << self def serialize_all ProductTaxonomy::Category.all_depth_first.each_with_object({}) do |category, groups| parent_id = category.parent&.gid.presence || "root" sibling = serialize(category) groups[category.level] ||= {} groups[category.level][parent_id] ||= [] groups[category.level][parent_id] << sibling end end # @param [Category] category # @return [Hash] def serialize(category) { "id" => category.gid, "name" => category.name, "fully_qualified_type" => category.full_name, "depth" => category.level, "parent_id" => category.parent&.gid.presence || "root", "node_type" => category.root? ? "root" : "leaf", "ancestor_ids" => category.ancestors.map(&:gid).join(","), "attribute_handles" => category.attributes.map(&:handle).join(","), } end end end end end end end
ruby
MIT
a1cb6132c9c0885c88ecbda53777f1dfc0e064d9
2026-01-04T17:02:35.318003Z
false
Shopify/product-taxonomy
https://github.com/Shopify/product-taxonomy/blob/a1cb6132c9c0885c88ecbda53777f1dfc0e064d9/dev/lib/product_taxonomy/models/serializers/category/docs/search_serializer.rb
dev/lib/product_taxonomy/models/serializers/category/docs/search_serializer.rb
# frozen_string_literal: true module ProductTaxonomy module Serializers module Category module Docs module SearchSerializer class << self def serialize_all ProductTaxonomy::Category.all_depth_first.flat_map { serialize(_1) } end # @param [Category] category # @return [Hash] def serialize(category) { "searchIdentifier" => category.gid, "title" => category.full_name, "url" => "?categoryId=#{CGI.escapeURIComponent(category.gid)}", "category" => { "id" => category.gid, "name" => category.name, "fully_qualified_type" => category.full_name, "depth" => category.level, }, } end end end end end end end
ruby
MIT
a1cb6132c9c0885c88ecbda53777f1dfc0e064d9
2026-01-04T17:02:35.318003Z
false
Shopify/product-taxonomy
https://github.com/Shopify/product-taxonomy/blob/a1cb6132c9c0885c88ecbda53777f1dfc0e064d9/dev/lib/product_taxonomy/models/serializers/category/dist/json_serializer.rb
dev/lib/product_taxonomy/models/serializers/category/dist/json_serializer.rb
# frozen_string_literal: true module ProductTaxonomy module Serializers module Category module Dist module JsonSerializer class << self def serialize_all(version:, locale: "en") { "version" => version, "verticals" => ProductTaxonomy::Category.verticals.map do |vertical| { "name" => vertical.name(locale:), "prefix" => vertical.id, "categories" => vertical.descendants_and_self.map { |category| serialize(category, locale:) }, } end, } end # @param category [Category] # @param locale [String] The locale to use for localization. # @return [Hash] def serialize(category, locale: "en") { "id" => category.gid, "level" => category.level, "name" => category.name(locale:), "full_name" => category.full_name(locale:), "parent_id" => category.parent&.gid, "attributes" => category.attributes.map do |attr| { "id" => attr.gid, "name" => attr.name(locale:), "handle" => attr.handle, "description" => attr.description(locale:), "extended" => attr.is_a?(ExtendedAttribute), } end, "children" => category.children.map do |child| { "id" => child.gid, "name" => child.name(locale:), } end, "ancestors" => category.ancestors.map do |ancestor| { "id" => ancestor.gid, "name" => ancestor.name(locale:), } end, } end end end end end end end
ruby
MIT
a1cb6132c9c0885c88ecbda53777f1dfc0e064d9
2026-01-04T17:02:35.318003Z
false
Shopify/product-taxonomy
https://github.com/Shopify/product-taxonomy/blob/a1cb6132c9c0885c88ecbda53777f1dfc0e064d9/dev/lib/product_taxonomy/models/serializers/category/dist/txt_serializer.rb
dev/lib/product_taxonomy/models/serializers/category/dist/txt_serializer.rb
# frozen_string_literal: true module ProductTaxonomy module Serializers module Category module Dist module TxtSerializer class << self def serialize_all(version:, locale: "en", padding: longest_gid_length) header = <<~HEADER # Shopify Product Taxonomy - Categories: #{version} # Format: {GID} : {Ancestor name} > ... > {Category name} HEADER categories_txt = ProductTaxonomy::Category .all_depth_first .map { |category| serialize(category, padding:, locale:) } .join("\n") header + categories_txt end # @param category [Category] # @param padding [Integer] The padding to use for the GID. # @param locale [String] The locale to use for localization. # @return [String] def serialize(category, padding:, locale: "en") "#{category.gid.ljust(padding)} : #{category.full_name(locale:)}" end private def longest_gid_length ProductTaxonomy::Category.all.max_by { |c| c.gid.length }.gid.length end end end end end end end
ruby
MIT
a1cb6132c9c0885c88ecbda53777f1dfc0e064d9
2026-01-04T17:02:35.318003Z
false
Shopify/product-taxonomy
https://github.com/Shopify/product-taxonomy/blob/a1cb6132c9c0885c88ecbda53777f1dfc0e064d9/dev/lib/product_taxonomy/models/serializers/category/data/data_serializer.rb
dev/lib/product_taxonomy/models/serializers/category/data/data_serializer.rb
# frozen_string_literal: true module ProductTaxonomy module Serializers module Category module Data module DataSerializer class << self def serialize_all(root = nil) categories = root ? root.descendants_and_self : ProductTaxonomy::Category.all_depth_first categories.sort_by(&:id_parts).flat_map { serialize(_1) } end # @param [Category] category # @return [Hash] def serialize(category) { "id" => category.id, "name" => category.name, "children" => category.children.sort_by(&:id_parts).map(&:id), "attributes" => AlphanumericSorter.sort(category.attributes.map(&:friendly_id), other_last: true), } end end end end end end end
ruby
MIT
a1cb6132c9c0885c88ecbda53777f1dfc0e064d9
2026-01-04T17:02:35.318003Z
false
Shopify/product-taxonomy
https://github.com/Shopify/product-taxonomy/blob/a1cb6132c9c0885c88ecbda53777f1dfc0e064d9/dev/lib/product_taxonomy/models/serializers/category/data/localizations_serializer.rb
dev/lib/product_taxonomy/models/serializers/category/data/localizations_serializer.rb
# frozen_string_literal: true module ProductTaxonomy module Serializers module Category module Data module LocalizationsSerializer class << self def serialize_all categories = ProductTaxonomy::Category.all_depth_first { "en" => { "categories" => categories.sort_by(&:id_parts).reduce({}) { _1.merge!(serialize(_2)) }, }, } end # @param [Category] category # @return [Hash] def serialize(category) { category.id => { "name" => category.name, "context" => category.full_name, }, } end end end end end end end
ruby
MIT
a1cb6132c9c0885c88ecbda53777f1dfc0e064d9
2026-01-04T17:02:35.318003Z
false
Shopify/product-taxonomy
https://github.com/Shopify/product-taxonomy/blob/a1cb6132c9c0885c88ecbda53777f1dfc0e064d9/dev/lib/product_taxonomy/models/serializers/category/data/full_names_serializer.rb
dev/lib/product_taxonomy/models/serializers/category/data/full_names_serializer.rb
# frozen_string_literal: true module ProductTaxonomy module Serializers module Category module Data module FullNamesSerializer class << self def serialize_all ProductTaxonomy::Category.all.sort_by(&:full_name).map { serialize(_1) } end # @param [Category] category # @return [Hash] def serialize(category) { "id" => category.id, "full_name" => category.full_name, } end end end end end end end
ruby
MIT
a1cb6132c9c0885c88ecbda53777f1dfc0e064d9
2026-01-04T17:02:35.318003Z
false
Shopify/product-taxonomy
https://github.com/Shopify/product-taxonomy/blob/a1cb6132c9c0885c88ecbda53777f1dfc0e064d9/dev/lib/product_taxonomy/models/serializers/value/dist/json_serializer.rb
dev/lib/product_taxonomy/models/serializers/value/dist/json_serializer.rb
# frozen_string_literal: true module ProductTaxonomy module Serializers module Value module Dist class JsonSerializer class << self def serialize_all(version:, locale: "en") { "version" => version, "values" => ProductTaxonomy::Value.all_values_sorted.map { serialize(_1, locale:) }, } end # @param value [Value] # @param locale [String] The locale to use for localization. # @return [Hash] def serialize(value, locale: "en") { "id" => value.gid, "name" => value.name(locale:), "handle" => value.handle, } end end end end end end end
ruby
MIT
a1cb6132c9c0885c88ecbda53777f1dfc0e064d9
2026-01-04T17:02:35.318003Z
false
Shopify/product-taxonomy
https://github.com/Shopify/product-taxonomy/blob/a1cb6132c9c0885c88ecbda53777f1dfc0e064d9/dev/lib/product_taxonomy/models/serializers/value/dist/txt_serializer.rb
dev/lib/product_taxonomy/models/serializers/value/dist/txt_serializer.rb
# frozen_string_literal: true module ProductTaxonomy module Serializers module Value module Dist class TxtSerializer class << self def serialize_all(version:, locale: "en", padding: longest_gid_length) header = <<~HEADER # Shopify Product Taxonomy - Attribute Values: #{version} # Format: {GID} : {Value name} [{Attribute name}] HEADER header + ProductTaxonomy::Value.all_values_sorted.map { serialize(_1, padding:, locale:) }.join("\n") end # @param value [Value] # @param padding [Integer] The padding to use for the GID. # @param locale [String] The locale to use for localization. # @return [String] def serialize(value, padding: 0, locale: "en") "#{value.gid.ljust(padding)} : #{value.full_name(locale:)}" end private def longest_gid_length largest_id = ProductTaxonomy::Value.hashed_by(:id).keys.max ProductTaxonomy::Value.find_by(id: largest_id).gid.length end end end end end end end
ruby
MIT
a1cb6132c9c0885c88ecbda53777f1dfc0e064d9
2026-01-04T17:02:35.318003Z
false
Shopify/product-taxonomy
https://github.com/Shopify/product-taxonomy/blob/a1cb6132c9c0885c88ecbda53777f1dfc0e064d9/dev/lib/product_taxonomy/models/serializers/value/data/data_serializer.rb
dev/lib/product_taxonomy/models/serializers/value/data/data_serializer.rb
# frozen_string_literal: true module ProductTaxonomy module Serializers module Value module Data module DataSerializer class << self def serialize_all ProductTaxonomy::Value.all.sort_by(&:id).map { serialize(_1) } end # @param [Value] value # @return [Hash] def serialize(value) { "id" => value.id, "name" => value.name, "friendly_id" => value.friendly_id, "handle" => value.handle, } end end end end end end end
ruby
MIT
a1cb6132c9c0885c88ecbda53777f1dfc0e064d9
2026-01-04T17:02:35.318003Z
false
Shopify/product-taxonomy
https://github.com/Shopify/product-taxonomy/blob/a1cb6132c9c0885c88ecbda53777f1dfc0e064d9/dev/lib/product_taxonomy/models/serializers/value/data/localizations_serializer.rb
dev/lib/product_taxonomy/models/serializers/value/data/localizations_serializer.rb
# frozen_string_literal: true module ProductTaxonomy module Serializers module Value module Data module LocalizationsSerializer class << self def serialize_all values = ProductTaxonomy::Value.all { "en" => { "values" => values.sort_by(&:friendly_id).reduce({}) { _1.merge!(serialize(_2)) }, }, } end # @param [Value] value # @return [Hash] def serialize(value) { value.friendly_id => { "name" => value.name, "context" => value.primary_attribute.name, }, } end end end end end end end
ruby
MIT
a1cb6132c9c0885c88ecbda53777f1dfc0e064d9
2026-01-04T17:02:35.318003Z
false
Shopify/product-taxonomy
https://github.com/Shopify/product-taxonomy/blob/a1cb6132c9c0885c88ecbda53777f1dfc0e064d9/dev/lib/product_taxonomy/models/serializers/attribute/docs/search_serializer.rb
dev/lib/product_taxonomy/models/serializers/attribute/docs/search_serializer.rb
# frozen_string_literal: true module ProductTaxonomy module Serializers module Attribute module Docs module SearchSerializer class << self def serialize_all ProductTaxonomy::Attribute.all.sort_by(&:name).map do |attribute| serialize(attribute) end end # @param [Attribute] attribute # @return [Hash] def serialize(attribute) { "searchIdentifier" => attribute.handle, "title" => attribute.name, "url" => "?attributeHandle=#{attribute.handle}", "attribute" => { "handle" => attribute.handle, }, } end end end end end end end
ruby
MIT
a1cb6132c9c0885c88ecbda53777f1dfc0e064d9
2026-01-04T17:02:35.318003Z
false
Shopify/product-taxonomy
https://github.com/Shopify/product-taxonomy/blob/a1cb6132c9c0885c88ecbda53777f1dfc0e064d9/dev/lib/product_taxonomy/models/serializers/attribute/docs/base_and_extended_serializer.rb
dev/lib/product_taxonomy/models/serializers/attribute/docs/base_and_extended_serializer.rb
# frozen_string_literal: true module ProductTaxonomy module Serializers module Attribute module Docs module BaseAndExtendedSerializer class << self def serialize_all ProductTaxonomy::Attribute.sorted_base_attributes.flat_map do |attribute| extended_attributes = attribute.extended_attributes.sort_by(&:name).map do |extended_attribute| serialize(extended_attribute) end extended_attributes + [serialize(attribute)] end end # @param [Attribute] attribute # @return [Hash] def serialize(attribute) result = { "id" => attribute.gid, "name" => attribute.extended? ? attribute.base_attribute.name : attribute.name, "handle" => attribute.handle, "extended_name" => attribute.extended? ? attribute.name : nil, "values" => attribute.values.map do |value| { "id" => value.gid, "name" => value.name, } end, } result.delete("extended_name") unless attribute.extended? result end end end end end end end
ruby
MIT
a1cb6132c9c0885c88ecbda53777f1dfc0e064d9
2026-01-04T17:02:35.318003Z
false
Shopify/product-taxonomy
https://github.com/Shopify/product-taxonomy/blob/a1cb6132c9c0885c88ecbda53777f1dfc0e064d9/dev/lib/product_taxonomy/models/serializers/attribute/docs/reversed_serializer.rb
dev/lib/product_taxonomy/models/serializers/attribute/docs/reversed_serializer.rb
# frozen_string_literal: true module ProductTaxonomy module Serializers module Attribute module Docs module ReversedSerializer class << self def serialize_all attributes_to_categories = ProductTaxonomy::Category.all.each_with_object({}) do |category, hash| category.attributes.each do |attribute| hash[attribute] ||= [] hash[attribute] << category end end serialized_attributes = ProductTaxonomy::Attribute.all.sort_by(&:name).map do |attribute| serialize(attribute, attributes_to_categories[attribute]) end { "attributes" => serialized_attributes, } end # @param [Attribute] attribute The attribute to serialize. # @param [Array<Category>] attribute_categories The categories that the attribute belongs to. # @return [Hash] The serialized attribute. def serialize(attribute, attribute_categories) attribute_categories ||= [] { "id" => attribute.gid, "handle" => attribute.handle, "name" => attribute.name, "base_name" => attribute.extended? ? attribute.base_attribute.name : nil, "categories" => attribute_categories.sort_by(&:full_name).map do |category| { "id" => category.gid, "full_name" => category.full_name, } end, "values" => attribute.sorted_values.map do |value| { "id" => value.gid, "name" => value.name, } end, } end end end end end end end
ruby
MIT
a1cb6132c9c0885c88ecbda53777f1dfc0e064d9
2026-01-04T17:02:35.318003Z
false
Shopify/product-taxonomy
https://github.com/Shopify/product-taxonomy/blob/a1cb6132c9c0885c88ecbda53777f1dfc0e064d9/dev/lib/product_taxonomy/models/serializers/attribute/dist/json_serializer.rb
dev/lib/product_taxonomy/models/serializers/attribute/dist/json_serializer.rb
# frozen_string_literal: true module ProductTaxonomy module Serializers module Attribute module Dist class JsonSerializer class << self def serialize_all(version:, locale: "en") { "version" => version, "attributes" => ProductTaxonomy::Attribute.sorted_base_attributes.map { serialize(_1, locale:) }, } end # @param attribute [Attribute] # @param locale [String] The locale to use for localized attributes. # @return [Hash] def serialize(attribute, locale: "en") { "id" => attribute.gid, "name" => attribute.name(locale:), "handle" => attribute.handle, "description" => attribute.description(locale:), "extended_attributes" => attribute.extended_attributes.sort_by(&:name).map do |ext_attr| { "name" => ext_attr.name(locale:), "handle" => ext_attr.handle, } end, "values" => attribute.sorted_values(locale:).map do |value| Serializers::Value::Dist::JsonSerializer.serialize(value, locale:) end, } end end end end end end end
ruby
MIT
a1cb6132c9c0885c88ecbda53777f1dfc0e064d9
2026-01-04T17:02:35.318003Z
false
Shopify/product-taxonomy
https://github.com/Shopify/product-taxonomy/blob/a1cb6132c9c0885c88ecbda53777f1dfc0e064d9/dev/lib/product_taxonomy/models/serializers/attribute/dist/txt_serializer.rb
dev/lib/product_taxonomy/models/serializers/attribute/dist/txt_serializer.rb
# frozen_string_literal: true module ProductTaxonomy module Serializers module Attribute module Dist class TxtSerializer class << self def serialize_all(version:, locale: "en", padding: longest_gid_length) header = <<~HEADER # Shopify Product Taxonomy - Attributes: #{version} # Format: {GID} : {Attribute name} HEADER attributes_txt = ProductTaxonomy::Attribute .sorted_base_attributes .map { serialize(_1, padding:, locale:) } .join("\n") header + attributes_txt end # @param attribute [Attribute] # @param padding [Integer] The padding to use for the GID. # @param locale [String] The locale to use for localized attributes. # @return [String] def serialize(attribute, padding: 0, locale: "en") "#{attribute.gid.ljust(padding)} : #{attribute.name(locale:)}" end private def longest_gid_length ProductTaxonomy::Attribute.all.filter_map { _1.extended? ? nil : _1.gid.length }.max end end end end end end end
ruby
MIT
a1cb6132c9c0885c88ecbda53777f1dfc0e064d9
2026-01-04T17:02:35.318003Z
false
Shopify/product-taxonomy
https://github.com/Shopify/product-taxonomy/blob/a1cb6132c9c0885c88ecbda53777f1dfc0e064d9/dev/lib/product_taxonomy/models/serializers/attribute/data/data_serializer.rb
dev/lib/product_taxonomy/models/serializers/attribute/data/data_serializer.rb
# frozen_string_literal: true module ProductTaxonomy module Serializers module Attribute module Data module DataSerializer class << self def serialize_all # Base attributes are sorted by ID, extended attributes are sorted by the order they were added extended_attributes, base_attributes = ProductTaxonomy::Attribute.all.partition(&:extended?) base_attributes.sort_by!(&:id) { "base_attributes" => base_attributes.map { serialize(_1) }, "extended_attributes" => extended_attributes.map { serialize(_1) }, } end # @param [Attribute] attribute # @return [Hash] def serialize(attribute) if attribute.extended? { "name" => attribute.name, "handle" => attribute.handle, "description" => attribute.description, "friendly_id" => attribute.friendly_id, "values_from" => attribute.values_from.friendly_id, } else { "id" => attribute.id, "name" => attribute.name, "description" => attribute.description, "friendly_id" => attribute.friendly_id, "handle" => attribute.handle, "sorting" => attribute.manually_sorted? ? "custom" : nil, "values" => attribute.sorted_values.map(&:friendly_id), }.compact end end end end end end end end
ruby
MIT
a1cb6132c9c0885c88ecbda53777f1dfc0e064d9
2026-01-04T17:02:35.318003Z
false
Shopify/product-taxonomy
https://github.com/Shopify/product-taxonomy/blob/a1cb6132c9c0885c88ecbda53777f1dfc0e064d9/dev/lib/product_taxonomy/models/serializers/attribute/data/localizations_serializer.rb
dev/lib/product_taxonomy/models/serializers/attribute/data/localizations_serializer.rb
# frozen_string_literal: true module ProductTaxonomy module Serializers module Attribute module Data module LocalizationsSerializer class << self def serialize_all attributes = ProductTaxonomy::Attribute.all { "en" => { "attributes" => attributes.sort_by(&:friendly_id).reduce({}) { _1.merge!(serialize(_2)) }, }, } end # @param [Attribute] attribute # @return [Hash] def serialize(attribute) { attribute.friendly_id => { "name" => attribute.name, "description" => attribute.description, }, } end end end end end end end
ruby
MIT
a1cb6132c9c0885c88ecbda53777f1dfc0e064d9
2026-01-04T17:02:35.318003Z
false
Shopify/product-taxonomy
https://github.com/Shopify/product-taxonomy/blob/a1cb6132c9c0885c88ecbda53777f1dfc0e064d9/dev/lib/product_taxonomy/models/mixins/indexed.rb
dev/lib/product_taxonomy/models/mixins/indexed.rb
# frozen_string_literal: true module ProductTaxonomy # Mixin providing indexing for a model, using hashes to support fast uniqueness checks and lookups by field value. module Indexed NotFoundError = Class.new(StandardError) class << self # Keep track of which model class used "extend Indexed" so that the model can be subclassed while still storing # model objects in a shared index on the superclass. def extended(indexed_model_class) indexed_model_class.instance_variable_set(:@is_indexed, true) end end # Validator that checks for uniqueness of a field value across all models in a given index. class UniquenessValidator < ActiveModel::EachValidator def validate_each(record, attribute, value) if record.class.duplicate?(model: record, field: attribute) record.errors.add(attribute, :taken, message: "\"#{value}\" has already been used") end end end # Add a model to the index. # # @param model [Object] The model to add to the index. def add(model) hashed_models.keys.each do |field| hashed_models[field][model.send(field)] ||= [] hashed_models[field][model.send(field)] << model end end # Convenience method to create a model, validate it, and add it to the index. If the model is not valid, raise an # error. # # @param args [Array] The arguments to pass to the model's constructor. # @return [Object] The created model. def create_validate_and_add!(...) model = new(...) model.validate!(:create) add(model) model end # Check if a field value is a duplicate of an existing model. A model is considered to be a duplicate if it was # added after the first model with that value. # # @param model [Object] The model to check for uniqueness. # @param field [Symbol] The field to check for uniqueness. # @return [Boolean] Whether the value is unique. def duplicate?(model:, field:) raise ArgumentError, "Field not hashed: #{field}" unless hashed_models.key?(field) existing_models = hashed_models[field][model.send(field)] return false if existing_models.nil? existing_models.first != model end # Find a model by field value. Returns the first matching record or nil. Only works for fields marked unique. # # @param conditions [Hash] Hash of field-value pairs to search by # @return [Object, nil] The matching model or nil if not found def find_by(**conditions) field, value = conditions.first raise ArgumentError, "Field not hashed: #{field}" unless hashed_models.key?(field) hashed_models[field][value]&.first end # Find a model by field value. Returns the first matching record or raises an error if not found. Only works for # fields marked unique. # # @param conditions [Hash] Hash of field-value pairs to search by # @return [Object] The matching model def find_by!(**conditions) record = find_by(**conditions) return record if record field, value = conditions.first field = field.to_s.humanize(capitalize: false, keep_id_suffix: true) raise NotFoundError, "#{self.name.demodulize} with #{field} \"#{value}\" not found" end # Get the hash of models indexed by a given field. Only works for fields marked unique. # # @param field [Symbol] The field to get the hash for. # @return [Hash] The hash of models indexed by the given field. def hashed_by(field) raise ArgumentError, "Field not hashed: #{field}" unless hashed_models.key?(field) hashed_models[field] end # Get all models in the index. # # @return [Array<Object>] All models in the index. def all hashed_models.first[1].values.flatten end # Get the number of models in the index. # # @return [Integer] The number of models in the index. def size all.size end # Get the hash of hash of models, indexed by fields marked unique. # # @return [Hash] The hash of hash of models indexed by the fields marked unique. def hashed_models # If we're a subclass of the model class that originally extended Indexed, use the parent class' hashed_models. return superclass.hashed_models unless @is_indexed @hashed_models ||= unique_fields.each_with_object({}) do |field, hash| hash[field] = {} end end private def unique_fields _validators.select do |_, validators| validators.any? do |validator| validator.is_a?(UniquenessValidator) end end.keys end end end
ruby
MIT
a1cb6132c9c0885c88ecbda53777f1dfc0e064d9
2026-01-04T17:02:35.318003Z
false
Shopify/product-taxonomy
https://github.com/Shopify/product-taxonomy/blob/a1cb6132c9c0885c88ecbda53777f1dfc0e064d9/dev/lib/product_taxonomy/models/mixins/formatted_validation_errors.rb
dev/lib/product_taxonomy/models/mixins/formatted_validation_errors.rb
# frozen_string_literal: true module ProductTaxonomy module FormattedValidationErrors def validate!(...) super # Calls original ActiveModel::Validations#validate! rescue ActiveModel::ValidationError id_field_name = self.is_a?(Category) ? :id : :friendly_id id_value = self.send(id_field_name) formatted_error_details = self.errors.map do |error| attribute = error.attribute # Raw attribute name, e.g., :friendly_id message = error.message # Just the message part, e.g., "can't be blank" prefix = " • " prefix + (attribute == :base ? message : "#{attribute} #{message}") end.join("\n") raise ActiveModel::ValidationError.new(self), "Validation failed for #{self.class.name.demodulize.downcase} " \ "with #{id_field_name}=`#{id_value}`:\n#{formatted_error_details}" end end end
ruby
MIT
a1cb6132c9c0885c88ecbda53777f1dfc0e064d9
2026-01-04T17:02:35.318003Z
false
Shopify/product-taxonomy
https://github.com/Shopify/product-taxonomy/blob/a1cb6132c9c0885c88ecbda53777f1dfc0e064d9/dev/lib/product_taxonomy/models/mixins/localized.rb
dev/lib/product_taxonomy/models/mixins/localized.rb
# frozen_string_literal: true module ProductTaxonomy module Localized def localizations return @localizations if @localizations localization_path = File.expand_path( "localizations/#{localizations_humanized_model_name}/*.yml", ProductTaxonomy.data_path, ) @localizations = Dir.glob(localization_path).each_with_object({}) do |file, localizations| locale = File.basename(file, ".yml") localizations[locale] = YAML.safe_load_file(file).dig(locale, localizations_humanized_model_name) end end # Validate that all localizations are present for the given locales. If no locales are provided, all locales # will be validated. # # @param locales [Array<String>, nil] The locales to validate. If nil, all locales will be validated. def validate_localizations!(locales = nil) model_keys = all.map { |model| model.send(@localizations_keyed_by).to_s } locales_to_validate = locales || localizations.keys locales_to_validate.each do |locale| missing_localization_keys = model_keys.reject { |key| localizations.dig(locale, key, "name") } next if missing_localization_keys.empty? raise ArgumentError, "Missing or incomplete localizations for the following keys in " \ "localizations/#{localizations_humanized_model_name}/#{locale}.yml: #{missing_localization_keys.join(", ")}" end end private # Define methods that return localized attributes by fetching from localization YAML files. Values for the `en` # locale come directly from the model's attributes. # # For example, if the class localizes `name` and `description` attributes keyed by `friendly_id`: # # localized_attr_reader :name, :description, keyed_by: :friendly_id # # This will generate the following methods: # # name(locale: "en") # description(locale: "en") def localized_attr_reader(*attrs, keyed_by: :friendly_id) if @localizations_keyed_by.present? && @localizations_keyed_by != keyed_by raise ArgumentError, "Cannot localize attributes with different keyed_by values" end @localizations_keyed_by = keyed_by attrs.each do |attr| define_method(attr) do |locale: "en"| raw_value = instance_variable_get("@#{attr}") if locale == "en" raw_value else self.class.localizations.dig(locale, send(keyed_by).to_s, attr.to_s) || raw_value end end end end def localizations_humanized_model_name name.demodulize.humanize.downcase.pluralize end end end
ruby
MIT
a1cb6132c9c0885c88ecbda53777f1dfc0e064d9
2026-01-04T17:02:35.318003Z
false
Shopify/product-taxonomy
https://github.com/Shopify/product-taxonomy/blob/a1cb6132c9c0885c88ecbda53777f1dfc0e064d9/docs/_plugins/copy_search.rb
docs/_plugins/copy_search.rb
# frozen_string_literal: true Jekyll::Hooks.register(:site, :post_write) do |site| source_data_dir = File.join(site.source, "_data") site_dest = site.dest Dir.glob(File.join(source_data_dir, "*")).each do |version_dir| next unless File.directory?(version_dir) version = File.basename(version_dir) target_dir = File.join(site_dest, "releases", version) Dir.mkdir(target_dir) unless Dir.exist?(target_dir) ["search_index.json", "attribute_search_index.json"].each do |file| source_file = File.join(version_dir, file) target_file = File.join(target_dir, file) FileUtils.cp(source_file, target_file) if File.exist?(source_file) end end end
ruby
MIT
a1cb6132c9c0885c88ecbda53777f1dfc0e064d9
2026-01-04T17:02:35.318003Z
false