api_version.rb 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115
  1. # frozen_string_literal: true
  2. module ShopifyAPI
  3. class ApiVersion
  4. class UnknownVersion < StandardError; end
  5. class InvalidVersion < StandardError; end
  6. include Comparable
  7. def self.coerce_to_version(version_or_name)
  8. return version_or_name if version_or_name.is_a?(ApiVersion)
  9. @versions ||= {}
  10. @versions.fetch(version_or_name.to_s) do
  11. raise UnknownVersion, "#{version_or_name} is not in the defined version set: #{@versions.keys.join(', ')}"
  12. end
  13. end
  14. def self.define_version(version)
  15. @versions ||= {}
  16. @versions[version.name] = version
  17. end
  18. def self.clear_defined_versions
  19. @versions = {}
  20. end
  21. def self.define_known_versions
  22. define_version(Unstable.new)
  23. end
  24. def self.latest_stable_version
  25. @versions.values.select(&:stable?).sort.last
  26. end
  27. def to_s
  28. @version_name
  29. end
  30. alias_method :name, :to_s
  31. def inspect
  32. @version_name
  33. end
  34. def ==(other)
  35. other.class == self.class && to_s == other.to_s
  36. end
  37. def hash
  38. @version_name.hash
  39. end
  40. def <=>(other)
  41. numeric_version <=> other.numeric_version
  42. end
  43. def stable?
  44. false
  45. end
  46. def construct_api_path(_path)
  47. raise NotImplementedError
  48. end
  49. def construct_graphql_path
  50. raise NotImplementedError
  51. end
  52. protected
  53. attr_reader :numeric_version
  54. class Unstable < ApiVersion
  55. API_PREFIX = '/admin/api/unstable/'
  56. def initialize
  57. @version_name = "unstable"
  58. @url = API_PREFIX
  59. @numeric_version = 9_000_00
  60. end
  61. def construct_api_path(path)
  62. "#{@url}#{path}"
  63. end
  64. def construct_graphql_path
  65. construct_api_path("graphql.json")
  66. end
  67. end
  68. class Release < ApiVersion
  69. FORMAT = /^\d{4}-\d{2}$/.freeze
  70. API_PREFIX = '/admin/api/'
  71. def initialize(version_number)
  72. raise InvalidVersion, version_number unless version_number.match(FORMAT)
  73. @version_name = version_number
  74. @url = "#{API_PREFIX}#{version_number}/"
  75. @numeric_version = version_number.tr('-', '').to_i
  76. end
  77. def stable?
  78. true
  79. end
  80. def construct_api_path(path)
  81. "#{@url}#{path}"
  82. end
  83. def construct_graphql_path
  84. construct_api_path('graphql.json')
  85. end
  86. end
  87. end
  88. end