Module: EasyTalk::Schema::InstanceMethods
- Defined in:
- lib/easy_talk/schema.rb
Overview
Instance methods for schema-only models.
Instance Method Summary collapse
-
#==(other) ⇒ Boolean
Allow comparison with hashes.
-
#as_json(_options = {}) ⇒ Hash
Convert to JSON-compatible hash including additional properties.
-
#initialize(attributes = {}) ⇒ Object
Initialize the schema object with attributes.
-
#to_h ⇒ Hash
Convert to hash including additional properties.
-
#to_hash ⇒ Hash
Convert defined properties to a hash.
Instance Method Details
#==(other) ⇒ Boolean
Allow comparison with hashes.
116 117 118 119 120 121 122 123 124 125 126 127 |
# File 'lib/easy_talk/schema.rb', line 116 def ==(other) case other when Hash self_hash = (self.class.schema_definition.schema[:properties] || {}).keys.each_with_object({}) do |prop, hash| hash[prop] = send(prop) end other_normalized = other.transform_keys(&:to_sym) self_hash == other_normalized else super end end |
#as_json(_options = {}) ⇒ Hash
Convert to JSON-compatible hash including additional properties.
101 102 103 |
# File 'lib/easy_talk/schema.rb', line 101 def as_json( = {}) to_hash.merge(@additional_properties) end |
#initialize(attributes = {}) ⇒ Object
Initialize the schema object with attributes.
55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 |
# File 'lib/easy_talk/schema.rb', line 55 def initialize(attributes = {}) @additional_properties = {} schema_def = self.class.schema_definition return unless schema_def.respond_to?(:schema) && schema_def.schema.is_a?(Hash) (schema_def.schema[:properties] || {}).each do |prop_name, prop_definition| value = attributes[prop_name] || attributes[prop_name.to_s] # Handle default values if value.nil? && !attributes.key?(prop_name) && !attributes.key?(prop_name.to_s) default_value = prop_definition.dig(:constraints, :default) value = default_value unless default_value.nil? end # Handle nested EasyTalk::Schema or EasyTalk::Model objects defined_type = prop_definition[:type] nilable_type = defined_type.respond_to?(:nilable?) && defined_type.nilable? defined_type = T::Utils::Nilable.(defined_type) if nilable_type if defined_type.is_a?(Class) && (defined_type.include?(EasyTalk::Schema) || defined_type.include?(EasyTalk::Model)) && value.is_a?(Hash) value = defined_type.new(value) end instance_variable_set("@#{prop_name}", value) end end |
#to_h ⇒ Hash
Convert to hash including additional properties.
108 109 110 |
# File 'lib/easy_talk/schema.rb', line 108 def to_h to_hash.merge(@additional_properties) end |
#to_hash ⇒ Hash
Convert defined properties to a hash.
88 89 90 91 92 93 94 95 |
# File 'lib/easy_talk/schema.rb', line 88 def to_hash properties_to_include = (self.class.schema_definition.schema[:properties] || {}).keys return {} if properties_to_include.empty? properties_to_include.each_with_object({}) do |prop, hash| hash[prop.to_s] = send(prop) end end |