Class: W3cApi::Models::CollectionBase
- Inherits:
-
Lutaml::Model::Serializable
- Object
- Lutaml::Model::Serializable
- W3cApi::Models::CollectionBase
- Extended by:
- DelegateEnumerable
- Defined in:
- lib/w3c_api/models/collection_base.rb
Direct Known Subclasses
Affiliations, Charters, Ecosystems, Groups, Participations, Series, SeriesCollection, SpecVersions, Specifications, Translations, Users
Class Method Summary collapse
- .collection_instance_class(klass, attribute) ⇒ Object
-
.from_response(data) ⇒ Object
Create a model instance from a hash response.
-
.transform_keys(data) ⇒ Object
Utility function to transform kebab-case to snake_case.
Methods included from DelegateEnumerable
Class Method Details
.collection_instance_class(klass, attribute) ⇒ Object
13 14 15 16 |
# File 'lib/w3c_api/models/collection_base.rb', line 13 def self.collection_instance_class(klass, attribute) @collection_instance_class ||= klass @collection_attribute = attribute end |
.from_response(data) ⇒ Object
Create a model instance from a hash response
19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 |
# File 'lib/w3c_api/models/collection_base.rb', line 19 def self.from_response(data) return new({ @collection_attribute => [] }) if data.nil? # Handle the case where data is expected to have 'items' key if data.is_a?(Hash) return new({ @collection_attribute => [] }) unless data.key?(:items) || data.key?('items') items_key = data.key?(:items) ? :items : 'items' items = data[items_key] || [] # Set pagination metadata result = new data.each do |key, value| next if key == items_key result.send("#{key}=", value) if result.respond_to?("#{key}=") end # Process items array transformed_items = items.map do |item| @collection_instance_class.new(transform_keys(item)) end result.send("#{@collection_attribute}=", transformed_items) return result # Handle case where response is a hash but doesn't contain 'items' end # Handle case where data is directly the items array if data.is_a?(Array) transformed_data = data.map do |item| @collection_instance_class.new(transform_keys(item)) end return new({ @collection_attribute => transformed_data }) end # For backward compatibility, try to create a model instance anyway new({ @collection_attribute => [] }) end |
.transform_keys(data) ⇒ Object
Utility function to transform kebab-case to snake_case
62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 |
# File 'lib/w3c_api/models/collection_base.rb', line 62 def self.transform_keys(data) case data when Hash result = {} data.each do |key, value| snake_key = key.to_s.tr('-', '_').to_sym result[snake_key] = transform_keys(value) end result when Array data.map { |item| transform_keys(item) } else data end end |