Module: JSONAPI::TypeConversion

Defined in:
lib/json_api/support/type_conversion.rb

Class Method Summary collapse

Class Method Details

.format_type_name(full_name, format) ⇒ Object



54
55
56
57
58
59
60
61
62
63
# File 'lib/json_api/support/type_conversion.rb', line 54

def format_type_name(full_name, format)
  case format
  when :prefixed
    full_name
  when :underscore
    full_name.tr("/", "_")
  else # :flat
    full_name.split("/").last
  end
end

.model_type_name(model_class, format: nil) ⇒ Object



36
37
38
39
40
41
42
43
# File 'lib/json_api/support/type_conversion.rb', line 36

def model_type_name(model_class, format: nil)
  format ||= JSONAPI.configuration.namespace_type_format
  name = model_class.name
  return format_type_name(name.underscore.pluralize, format) if name.nil?

  cache = TypeConversion.type_name_cache
  cache["m|#{name}|#{format}"] ||= format_type_name(name.underscore.pluralize, format).freeze
end

.prefixed_type_to_class(type_str) ⇒ Object



31
32
33
34
# File 'lib/json_api/support/type_conversion.rb', line 31

def prefixed_type_to_class(type_str)
  parts = type_str.split("/")
  "#{parts[0..-2].join("/").camelize}::#{parts.last.singularize.classify}"
end

.reset_cache!Object



13
14
15
# File 'lib/json_api/support/type_conversion.rb', line 13

def self.reset_cache!
  @type_name_cache.clear
end

.resolve_type_format(definition_class) ⇒ Object



65
66
67
68
69
70
71
# File 'lib/json_api/support/type_conversion.rb', line 65

def resolve_type_format(definition_class)
  if definition_class.respond_to?(:type_format) && definition_class.type_format
    definition_class.type_format
  else
    JSONAPI.configuration.namespace_type_format
  end
end

.resource_type_name(definition_class, format: nil) ⇒ Object



45
46
47
48
49
50
51
52
# File 'lib/json_api/support/type_conversion.rb', line 45

def resource_type_name(definition_class, format: nil)
  format ||= resolve_type_format(definition_class)
  name = definition_class.name
  return format_type_name(name.sub(/Resource$/, "").underscore.pluralize, format) if name.nil?

  cache = TypeConversion.type_name_cache
  cache["r|#{name}|#{format}"] ||= format_type_name(name.sub(/Resource$/, "").underscore.pluralize, format).freeze
end

.type_name_cacheObject



17
18
19
# File 'lib/json_api/support/type_conversion.rb', line 17

def self.type_name_cache
  @type_name_cache
end

.type_to_class_name(type, namespace: nil) ⇒ Object



23
24
25
26
27
28
29
# File 'lib/json_api/support/type_conversion.rb', line 23

def type_to_class_name(type, namespace: nil)
  type_str = type.to_s
  return prefixed_type_to_class(type_str) if type_str.include?("/")
  return "#{namespace.to_s.camelize}::#{type_str.singularize.classify}" if namespace.present?

  type_str.singularize.classify
end