Last active
August 21, 2023 13:19
-
-
Save max-did-it/3e6246255ac59e9d27a7ae4cf837ae44 to your computer and use it in GitHub Desktop.
Convert value by https://github.com/OAI/OpenAPI-Specification/blob/master/versions/3.0.1.md#dataTypes
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
module OpenApiTypeConverter | |
class << self | |
def short(value, field_name) | |
value = value.to_i | |
value.bit_length > 32 ? raise(ValueIsTooLargeForInt64, field_name) : value | |
end | |
def long(value, field_name) | |
value = value.to_i | |
value.bit_length > 64 ? raise(ValueIsTooLargeForInt64, field_name) : value | |
end | |
def float(value, _field_name) | |
value.to_f | |
end | |
def double(value, field_name) | |
value.to_d | |
end | |
def string(value, field_name) | |
"#{value}" | |
end | |
def byte(value, _field_name) | |
Base64.encode64(value.to_s) | |
end | |
def binary(value, _field_name) | |
value.to_s.bytes.map { |e| e.to_s(2) }.join(' ') | |
end | |
def boolean(value, _field_name) | |
!!value | |
end | |
def date_time(value, field_name) | |
prepared_val = case value | |
when Integer, BigDecimal, Float | |
Time.zone.at(value) | |
when Date, DateTime, Time | |
value | |
else | |
raise ValueHasIncorrectType.new("#{field_name} => #{value}") | |
end | |
prepared_val.rfc3339 | |
end | |
alias int64 long | |
alias int32 short | |
alias date date_time | |
end | |
class ValueIsTooLargeForInt32 < StandardError; end | |
class ValueIsTooLargeForInt64 < StandardError; end | |
class ValueHasIncorrectType < StandardError; end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment