api_version.rb 2.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116
  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. define_version(Release.new('2019-04'))
  24. end
  25. def self.latest_stable_version
  26. @versions.values.select(&:stable?).sort.last
  27. end
  28. def to_s
  29. @version_name
  30. end
  31. alias_method :name, :to_s
  32. def inspect
  33. @version_name
  34. end
  35. def ==(other)
  36. other.class == self.class && to_s == other.to_s
  37. end
  38. def hash
  39. @version_name.hash
  40. end
  41. def <=>(other)
  42. numeric_version <=> other.numeric_version
  43. end
  44. def stable?
  45. false
  46. end
  47. def construct_api_path(_path)
  48. raise NotImplementedError
  49. end
  50. def construct_graphql_path
  51. raise NotImplementedError
  52. end
  53. protected
  54. attr_reader :numeric_version
  55. class Unstable < ApiVersion
  56. API_PREFIX = '/admin/api/unstable/'
  57. def initialize
  58. @version_name = "unstable"
  59. @url = API_PREFIX
  60. @numeric_version = 9_000_00
  61. end
  62. def construct_api_path(path)
  63. "#{@url}#{path}"
  64. end
  65. def construct_graphql_path
  66. construct_api_path("graphql.json")
  67. end
  68. end
  69. class Release < ApiVersion
  70. FORMAT = /^\d{4}-\d{2}$/.freeze
  71. API_PREFIX = '/admin/api/'
  72. def initialize(version_number)
  73. raise InvalidVersion, version_number unless version_number.match(FORMAT)
  74. @version_name = version_number
  75. @url = "#{API_PREFIX}#{version_number}/"
  76. @numeric_version = version_number.tr('-', '').to_i
  77. end
  78. def stable?
  79. true
  80. end
  81. def construct_api_path(path)
  82. "#{@url}#{path}"
  83. end
  84. def construct_graphql_path
  85. construct_api_path('graphql.json')
  86. end
  87. end
  88. end
  89. end