tag.rb 2.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374
  1. module MachineTag
  2. # A tag which can be a machine tag.
  3. #
  4. class Tag < String
  5. # The regular expression for matching the namespace and predicate portions of a machine tag
  6. #
  7. # @return [Regexp] the regular expression for matching the namespace and predicate portions of a machine tag
  8. #
  9. PREFIX = /[a-z][a-z0-9_]*/i
  10. # The regular expression for matching a machine tag
  11. #
  12. # @return [Regexp] the regular expression for matching a machine tag
  13. #
  14. MACHINE_TAG = /^(?<namespace>#{PREFIX}):(?<predicate>#{PREFIX})=(?<value>.*)$/
  15. # The namespace portion of the machine tag, +nil+ if the tag is not a machine tag
  16. #
  17. # @return [String, nil] the namespace portion of the machine tag, +nil+ if the tag is not a machine tag
  18. #
  19. attr_reader :namespace
  20. # The predicate portion of the machine tag, +nil+ if the tag is not a machine tag
  21. #
  22. # @return [String, nil] the predicate portion of the machine tag, +nil+ if the tag is not a machine tag
  23. #
  24. attr_reader :predicate
  25. # The value portion of the machine tag, +nil+ if the tag is not a machine tag
  26. #
  27. # @return [String, nil] the value portion of the machine tag is not a machine tag
  28. #
  29. attr_reader :value
  30. # Creates a tag object which can be a machine tag.
  31. #
  32. # @param str [String] the tag string
  33. #
  34. def initialize(str)
  35. super
  36. if match = self.match(MACHINE_TAG)
  37. @namespace = match[:namespace]
  38. @predicate = match[:predicate]
  39. @value = match[:value]
  40. @value = $1 if @value =~ /^"(.*)"$/
  41. end
  42. end
  43. # Creates a machine tag from a given namespace, predicate, and value.
  44. #
  45. # @param namespace [String] the namespace
  46. # @param predicate [String] the predicate
  47. # @param value [String, #to_s] the value
  48. #
  49. # @return [Tag] the machine tag
  50. #
  51. # @raise [ArgumentError] if the +namespace+ or +predicate+ are not in the correct format
  52. #
  53. def self.machine_tag(namespace, predicate, value)
  54. raise ArgumentError, "Invalid machine tag namespace: #{namespace.inspect}" unless namespace =~ /^#{PREFIX}$/
  55. raise ArgumentError, "Invalid machine tag predicate: #{predicate.inspect}" unless predicate =~ /^#{PREFIX}$/
  56. new("#{namespace}:#{predicate}=#{value}")
  57. end
  58. # Returns whether this tag is a machine tag or not.
  59. #
  60. # @return [Boolean] +true+ if this tag is a machine tag, otherwise +false+
  61. #
  62. def machine_tag?
  63. !!namespace
  64. end
  65. end
  66. end