Class: Attributor::Hash
- Inherits:
-
Object
- Object
- Attributor::Hash
- Defined in:
- lib/attributor/types/hash.rb
Direct Known Subclasses
Constant Summary collapse
- MAX_EXAMPLE_DEPTH =
10
- CIRCULAR_REFERENCE_MARKER =
'...'.freeze
Class Attribute Summary collapse
-
.cached_defaults ⇒ Object
readonly
Returns the value of attribute cached_defaults.
-
.extra_keys ⇒ Object
Returns the value of attribute extra_keys.
-
.insensitive_map ⇒ Object
readonly
Returns the value of attribute insensitive_map.
-
.key_attribute ⇒ Object
readonly
Returns the value of attribute key_attribute.
-
.key_type ⇒ Object
Returns the value of attribute key_type.
-
.options ⇒ Object
readonly
Returns the value of attribute options.
-
.requirements ⇒ Object
readonly
Returns the value of attribute requirements.
-
.value_attribute ⇒ Object
readonly
Returns the value of attribute value_attribute.
-
.value_type ⇒ Object
Returns the value of attribute value_type.
Instance Attribute Summary collapse
-
#contents ⇒ Object
readonly
TODO: Think about the format of the subcontexts to use: let’s use .at(key.to_s).
-
#dumping ⇒ Object
readonly
Returns the value of attribute dumping.
-
#validating ⇒ Object
readonly
Returns the value of attribute validating.
Class Method Summary collapse
- .add_requirement(req) ⇒ Object
- .as_json_schema(shallow: false, example: nil, attribute_options: {}) ⇒ Object
- .attributes(**options, &key_spec) ⇒ Object
- .check_option!(name, _definition) ⇒ Object
- .construct(constructor_block, **options) ⇒ Object
- .constructable? ⇒ Boolean
- .definition ⇒ Object
- .describe(shallow = false, example: nil) ⇒ Object
- .dsl_class ⇒ Object
- .dump(value, **opts) ⇒ Object
- .example(context = nil, **values) ⇒ Object
- .example_contents(context, parent, **values) ⇒ Object
- .family ⇒ Object
- .from_hash(object, context, recurse: false) ⇒ Object
- .generate_subcontext(context, key_name) ⇒ Object
- .inherited(klass) ⇒ Object
- .json_schema_type ⇒ Object
- .keys(**options, &key_spec) ⇒ Object
- .load(value, context = Attributor::DEFAULT_ROOT_CONTEXT, recurse: false, **_options) ⇒ Object
- .load_generic(value, context) ⇒ Object
- .native_type ⇒ Object
- .of(key: @key_type, value: @value_type) ⇒ Object
- .parse(value, context) ⇒ Object
- .slice!(*keys) ⇒ Object
- .valid_type?(type) ⇒ Boolean
- .validate(object, context = Attributor::DEFAULT_ROOT_CONTEXT, _attribute) ⇒ Object
Instance Method Summary collapse
- #==(other) ⇒ Object
- #[](k) ⇒ Object
- #[]=(k, v) ⇒ Object
- #_get_attr(k) ⇒ Object
- #delete(key) ⇒ Object
- #dump(**opts) ⇒ Object
- #each(&block) ⇒ Object (also: #each_pair)
- #empty? ⇒ Boolean
- #generate_subcontext(context, key_name) ⇒ Object
- #get(key, context: generate_subcontext(Attributor::DEFAULT_ROOT_CONTEXT, key)) ⇒ Object
- #get_generic(key, context) ⇒ Object
-
#initialize(contents = {}) ⇒ Hash
constructor
A new instance of Hash.
- #key?(k) ⇒ Boolean (also: #has_key?)
- #key_attribute ⇒ Object
- #key_type ⇒ Object
- #keys ⇒ Object
- #merge(h) ⇒ Object
- #set(key, value, context: generate_subcontext(Attributor::DEFAULT_ROOT_CONTEXT, key), recurse: false) ⇒ Object
- #size ⇒ Object
- #to_h ⇒ Object
- #validate(context = Attributor::DEFAULT_ROOT_CONTEXT) ⇒ Object
- #validate_generic(context) ⇒ Object
- #validate_keys(context) ⇒ Object
- #value_attribute ⇒ Object
- #value_type ⇒ Object
- #values ⇒ Object
Methods included from Container
Constructor Details
#initialize(contents = {}) ⇒ Hash
Returns a new instance of Hash.
607 608 609 610 611 612 |
# File 'lib/attributor/types/hash.rb', line 607 def initialize(contents = {}) @validating = false @dumping = false @contents = contents end |
Class Attribute Details
.cached_defaults ⇒ Object (readonly)
Returns the value of attribute cached_defaults.
33 34 35 |
# File 'lib/attributor/types/hash.rb', line 33 def cached_defaults @cached_defaults end |
.extra_keys ⇒ Object
Returns the value of attribute extra_keys.
31 32 33 |
# File 'lib/attributor/types/hash.rb', line 31 def extra_keys @extra_keys end |
.insensitive_map ⇒ Object (readonly)
Returns the value of attribute insensitive_map.
30 31 32 |
# File 'lib/attributor/types/hash.rb', line 30 def insensitive_map @insensitive_map end |
.key_attribute ⇒ Object (readonly)
Returns the value of attribute key_attribute.
29 30 31 |
# File 'lib/attributor/types/hash.rb', line 29 def key_attribute @key_attribute end |
.key_type ⇒ Object
Returns the value of attribute key_type.
27 28 29 |
# File 'lib/attributor/types/hash.rb', line 27 def key_type @key_type end |
.options ⇒ Object (readonly)
Returns the value of attribute options.
27 28 29 |
# File 'lib/attributor/types/hash.rb', line 27 def @options end |
.requirements ⇒ Object (readonly)
Returns the value of attribute requirements.
32 33 34 |
# File 'lib/attributor/types/hash.rb', line 32 def requirements @requirements end |
.value_attribute ⇒ Object (readonly)
Returns the value of attribute value_attribute.
28 29 30 |
# File 'lib/attributor/types/hash.rb', line 28 def value_attribute @value_attribute end |
.value_type ⇒ Object
Returns the value of attribute value_type.
27 28 29 |
# File 'lib/attributor/types/hash.rb', line 27 def value_type @value_type end |
Instance Attribute Details
#contents ⇒ Object (readonly)
TODO: Think about the format of the subcontexts to use: let’s use .at(key.to_s)
541 542 543 |
# File 'lib/attributor/types/hash.rb', line 541 def contents @contents end |
#dumping ⇒ Object (readonly)
Returns the value of attribute dumping.
605 606 607 |
# File 'lib/attributor/types/hash.rb', line 605 def dumping @dumping end |
#validating ⇒ Object (readonly)
Returns the value of attribute validating.
605 606 607 |
# File 'lib/attributor/types/hash.rb', line 605 def validating @validating end |
Class Method Details
.add_requirement(req) ⇒ Object
161 162 163 164 165 166 167 168 169 |
# File 'lib/attributor/types/hash.rb', line 161 def self.add_requirement(req) @requirements << req return unless req.attr_names non_existing = req.attr_names - attributes.keys unless non_existing.empty? raise "Invalid attribute name(s) found (#{non_existing.join(', ')}) when defining a requirement of type #{req.type} for #{Attributor.type_name(self)} ." \ "The only existing attributes are #{attributes.keys}" end end |
.as_json_schema(shallow: false, example: nil, attribute_options: {}) ⇒ Object
486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 |
# File 'lib/attributor/types/hash.rb', line 486 def self.as_json_schema( shallow: false, example: nil, attribute_options: {} ) hash = super opts = self..merge( ) if key_type hash[:'x-key_type'] = key_type.as_json_schema end if self.keys.any? # Spit keys if it's the root or if it's an anonymous structures if ( !shallow || self.name == nil) required_names_from_attr = [] # FIXME: change to :keys when the praxis doc browser supports displaying those hash[:properties] = self.keys.each_with_object({}) do |(sub_name, sub_attribute), sub_attributes| required_names_from_attr << sub_name if sub_attribute.[:required] == true sub_example = example.get(sub_name) if example sub_attributes[sub_name] = sub_attribute.as_json_schema(shallow: true, example: sub_example) end # Expose the more complex requirements to in the x-tended attribute extended_requirements = self.requirements.each_with_object([]) do |req, list| described_req = req.describe(shallow) if described_req[:type] == :all # Add the names of the attributes that have the required flag too described_req[:attributes] |= required_names_from_attr required_names_from_attr = [] end list << described_req end all = extended_requirements.find{|r| r[:type] == :all } if ( all && !all[:attributes].empty? ) hash[:required] = all[:attributes] end hash[:'x-requirements'] = extended_requirements unless extended_requirements.empty? end else hash[:'x-value_type'] = value_type.as_json_schema(shallow:true) end if opts[:allow_extra] hash[:additionalProperties] = if value_type == Attributor::Object true else value_type.as_json_schema(shallow: true) end end # TODO: minProperties and maxProperties and patternProperties hash end |
.attributes(**options, &key_spec) ⇒ Object
91 92 93 94 95 |
# File 'lib/attributor/types/hash.rb', line 91 def self.attributes(**, &key_spec) raise @error if @error keys(**, &key_spec) end |
.check_option!(name, _definition) ⇒ Object
255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 |
# File 'lib/attributor/types/hash.rb', line 255 def self.check_option!(name, _definition) case name when :reference :ok # FIXME: ... actually do something smart when :dsl_compiler :ok when :case_insensitive_load unless key_type <= String raise Attributor::AttributorException, ":case_insensitive_load may not be used with keys of type #{key_type.name}" end :ok when :allow_extra :ok else :unknown end end |
.construct(constructor_block, **options) ⇒ Object
171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 |
# File 'lib/attributor/types/hash.rb', line 171 def self.construct(constructor_block, **) return self if constructor_block.nil? unless @concrete return of(key: key_type, value: value_type) .construct(constructor_block, **) end if [:case_insensitive_load] && !(key_type <= String) raise Attributor::AttributorException, ":case_insensitive_load may not be used with keys of type #{key_type.name}" end keys(**, &constructor_block) self end |
.constructable? ⇒ Boolean
157 158 159 |
# File 'lib/attributor/types/hash.rb', line 157 def self.constructable? true end |
.definition ⇒ Object
116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 |
# File 'lib/attributor/types/hash.rb', line 116 def self.definition opts = { key_type: @key_type, value_type: @value_type }.merge(@options) blocks = @saved_blocks.shift(@saved_blocks.size) compiler = dsl_class.new(self, **opts) compiler.parse(*blocks) if opts[:case_insensitive_load] == true @insensitive_map = keys.keys.each_with_object({}) do |k, map| map[k.downcase] = k end end rescue => e @error = InvalidDefinition.new(self, e) raise end |
.describe(shallow = false, example: nil) ⇒ Object
448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 |
# File 'lib/attributor/types/hash.rb', line 448 def self.describe(shallow = false, example: nil) hash = super(shallow) hash[:key] = { type: key_type.describe(true) } if key_type if keys.any? # Spit keys if it's the root or if it's an anonymous structures if ( !shallow || self.name == nil) required_names_from_attr = [] # FIXME: change to :keys when the praxis doc browser supports displaying those hash[:attributes] = self.keys.each_with_object({}) do |(sub_name, sub_attribute), sub_attributes| required_names_from_attr << sub_name if sub_attribute.[:required] == true sub_example = example.get(sub_name) if example sub_attributes[sub_name] = sub_attribute.describe(true, example: sub_example) end hash[:requirements] = requirements.each_with_object([]) do |req, list| described_req = req.describe(shallow) if described_req[:type] == :all # Add the names of the attributes that have the required flag too described_req[:attributes] |= required_names_from_attr required_names_from_attr = [] end list << described_req end # Make sure we create an :all requirement, if there wasn't one so we can add the required: true attributes unless required_names_from_attr.empty? hash[:requirements] << {type: :all, attributes: required_names_from_attr } end end else hash[:value] = { type: value_type.describe(true) } hash[:example] = example if example hash[:attributes] = {} end hash end |
.dsl_class ⇒ Object
136 137 138 |
# File 'lib/attributor/types/hash.rb', line 136 def self.dsl_class @options[:dsl_compiler] || HashDSLCompiler end |
.dump(value, **opts) ⇒ Object
249 250 251 252 253 |
# File 'lib/attributor/types/hash.rb', line 249 def self.dump(value, **opts) if (loaded = load(value)) loaded.dump(**opts) end end |
.example(context = nil, **values) ⇒ Object
223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 |
# File 'lib/attributor/types/hash.rb', line 223 def self.example(context = nil, **values) return new if key_type == Object && value_type == Object && keys.empty? context ||= ["#{Hash}-#{rand(10_000_000)}"] context = Array(context) if keys.any? result = new result.extend(ExampleMixin) result.lazy_attributes = example_contents(context, result, **values) else hash = ::Hash.new (rand(3) + 1).times do |i| example_key = key_type.example(context + ["at(#{i})"]) subcontext = context + ["at(#{example_key})"] hash[example_key] = value_type.example(subcontext) end result = new(hash) end result end |
.example_contents(context, parent, **values) ⇒ Object
189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 |
# File 'lib/attributor/types/hash.rb', line 189 def self.example_contents(context, parent, **values) hash = ::Hash.new example_depth = context.size # Be smart about what attributes to use for the example: i.e. have into account complex requirements # that might have been defined in the hash like at_most(1).of ..., exactly(2).of ...etc. # But play it safe and default to the previous behavior in case there is any error processing them # ( that is until the SmartAttributeSelector class isn't fully tested and ready for prime time) begin stack = SmartAttributeSelector.new( requirements.map(&:describe), keys.keys , values) selected = stack.process rescue => e selected = keys.keys end keys.select{|n,attr| selected.include? n}.each do |sub_attribute_name, sub_attribute| if sub_attribute.attributes # TODO: add option to raise an exception in this case? next if example_depth > MAX_EXAMPLE_DEPTH end sub_context = generate_subcontext(context, sub_attribute_name) block = proc do value = values.fetch(sub_attribute_name) do sub_attribute.example(sub_context, parent: parent) end sub_attribute.load(value, sub_context) end hash[sub_attribute_name] = block end hash end |
.family ⇒ Object
65 66 67 |
# File 'lib/attributor/types/hash.rb', line 65 def self.family 'hash' end |
.from_hash(object, context, recurse: false) ⇒ Object
401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 |
# File 'lib/attributor/types/hash.rb', line 401 def self.from_hash(object, context, recurse: false) hash = new # if the hash definition includes named extra keys, initialize # its value from the object in case it provides some already. # this is to ensure it exists when we handle any extra keys # that may exist in the object later if extra_keys sub_context = generate_subcontext(context, extra_keys) v = object.fetch(extra_keys, {}) hash.set(extra_keys, v, context: sub_context, recurse: recurse) end object.each do |k, val| next if k == extra_keys sub_context = generate_subcontext(context, k) hash.set(k, val, context: sub_context, recurse: recurse) end # handle default values for missing keys keys.each do |key_name, attribute| next if hash.key?(key_name) # Cache default values to avoid a whole loading call for the attribute default = if @cached_defaults.key?(key_name) @cached_defaults[key_name] else sub_context = generate_subcontext(context, key_name) @cached_defaults[key_name] = attribute.load(nil, sub_context, recurse: recurse) end hash[key_name] = default unless default.nil? end hash end |
.generate_subcontext(context, key_name) ⇒ Object
311 312 313 |
# File 'lib/attributor/types/hash.rb', line 311 def self.generate_subcontext(context, key_name) context + ["key(#{key_name.inspect})"] end |
.inherited(klass) ⇒ Object
73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 |
# File 'lib/attributor/types/hash.rb', line 73 def self.inherited(klass) k = key_type v = value_type klass.instance_eval do @saved_blocks = [] @options = { allow_extra: false } @keys = {} @key_type = k @value_type = v @key_attribute = Attribute.new(@key_type) @value_attribute = Attribute.new(@value_type) @requirements = [] @cached_defaults = {} @error = false end end |
.json_schema_type ⇒ Object
536 537 538 |
# File 'lib/attributor/types/hash.rb', line 536 def self.json_schema_type :object end |
.keys(**options, &key_spec) ⇒ Object
97 98 99 100 101 102 103 104 105 106 107 |
# File 'lib/attributor/types/hash.rb', line 97 def self.keys(**, &key_spec) raise @error if @error if block_given? @saved_blocks << key_spec @options.merge!() elsif @saved_blocks.any? definition end @keys end |
.load(value, context = Attributor::DEFAULT_ROOT_CONTEXT, recurse: false, **_options) ⇒ Object
273 274 275 276 277 278 279 280 281 282 283 |
# File 'lib/attributor/types/hash.rb', line 273 def self.load(value, context = Attributor::DEFAULT_ROOT_CONTEXT, recurse: false, **) return value if value.is_a?(self) return nil if value.nil? && !recurse context = Array(context) loaded_value = self.parse(value, context) return from_hash(loaded_value, context, recurse: recurse) if keys.any? load_generic(loaded_value, context) end |
.load_generic(value, context) ⇒ Object
303 304 305 306 307 308 309 |
# File 'lib/attributor/types/hash.rb', line 303 def self.load_generic(value, context) return new(value) if key_type == Object && value_type == Object value.each_with_object(new) do |(k, v), obj| obj[key_type.load(k, context)] = value_type.load(v, context) end end |
.native_type ⇒ Object
140 141 142 |
# File 'lib/attributor/types/hash.rb', line 140 def self.native_type self end |
.of(key: @key_type, value: @value_type) ⇒ Object
149 150 151 152 153 154 155 |
# File 'lib/attributor/types/hash.rb', line 149 def self.of(key: @key_type, value: @value_type) ::Class.new(self) do self.key_type = key self.value_type = value @keys = {} end end |
.parse(value, context) ⇒ Object
285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 |
# File 'lib/attributor/types/hash.rb', line 285 def self.parse(value, context) if value.nil? {} elsif value.is_a?(Attributor::Hash) value.contents elsif value.is_a?(::Hash) value elsif value.is_a?(::String) decode_json(value, context) elsif value.respond_to?(:to_h) value.to_h elsif value.respond_to?(:to_hash) # Deprecate this in lieu of to_h only? value.to_hash else raise Attributor::IncompatibleTypeError.new(context: context, value_type: value.class, type: self) end end |
.slice!(*keys) ⇒ Object
46 47 48 49 50 51 |
# File 'lib/attributor/types/hash.rb', line 46 def self.slice!(*keys) missing_keys = keys - @keys.keys raise AttributorException, "Cannot slice! this type, because it does not contain one or more of the requested keys: #{missing_keys}" unless missing_keys.empty? instance_variable_set(:@keys, @keys.slice(*keys)) self end |
.valid_type?(type) ⇒ Boolean
144 145 146 |
# File 'lib/attributor/types/hash.rb', line 144 def self.valid_type?(type) type.is_a?(self) || type.is_a?(::Hash) end |
.validate(object, context = Attributor::DEFAULT_ROOT_CONTEXT, _attribute) ⇒ Object
439 440 441 442 443 444 445 446 |
# File 'lib/attributor/types/hash.rb', line 439 def self.validate(object, context = Attributor::DEFAULT_ROOT_CONTEXT, _attribute) context = [context] if context.is_a? ::String unless object.is_a?(self) raise ArgumentError, "#{name} can not validate object of type #{object.class.name} for #{Attributor.humanize_context(context)}." end object.validate(context) end |
Instance Method Details
#==(other) ⇒ Object
630 631 632 |
# File 'lib/attributor/types/hash.rb', line 630 def ==(other) contents == other || (other.respond_to?(:contents) ? contents == other.contents : false) end |
#[](k) ⇒ Object
543 544 545 |
# File 'lib/attributor/types/hash.rb', line 543 def [](k) @contents[k] end |
#[]=(k, v) ⇒ Object
551 552 553 |
# File 'lib/attributor/types/hash.rb', line 551 def []=(k, v) @contents[k] = v end |
#_get_attr(k) ⇒ Object
547 548 549 |
# File 'lib/attributor/types/hash.rb', line 547 def _get_attr(k) self[k] end |
#delete(key) ⇒ Object
601 602 603 |
# File 'lib/attributor/types/hash.rb', line 601 def delete(key) @contents.delete(key) end |
#dump(**opts) ⇒ Object
702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 |
# File 'lib/attributor/types/hash.rb', line 702 def dump(**opts) return CIRCULAR_REFERENCE_MARKER if @dumping @dumping = true contents.each_with_object({}) do |(k, v), hash| k = key_attribute.dump(k, **opts) v = if (attribute_for_value = self.class.keys[k]) attribute_for_value.dump(v, **opts) else value_attribute.dump(v, **opts) end hash[k] = v end ensure @dumping = false end |
#each(&block) ⇒ Object Also known as: each_pair
555 556 557 |
# File 'lib/attributor/types/hash.rb', line 555 def each(&block) @contents.each(&block) end |
#empty? ⇒ Boolean
573 574 575 |
# File 'lib/attributor/types/hash.rb', line 573 def empty? @contents.empty? end |
#generate_subcontext(context, key_name) ⇒ Object
319 320 321 |
# File 'lib/attributor/types/hash.rb', line 319 def generate_subcontext(context, key_name) self.class.generate_subcontext(context, key_name) end |
#get(key, context: generate_subcontext(Attributor::DEFAULT_ROOT_CONTEXT, key)) ⇒ Object
323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 |
# File 'lib/attributor/types/hash.rb', line 323 def get(key, context: generate_subcontext(Attributor::DEFAULT_ROOT_CONTEXT, key)) key = self.class.key_attribute.load(key, context) return self.get_generic(key, context) if self.class.keys.empty? value = @contents[key] # FIXME: getting an unset value here should not force it in the hash if (attribute = self.class.keys[key]) loaded_value = attribute.load(value, context) return nil if loaded_value.nil? return self[key] = loaded_value end if self.class.[:case_insensitive_load] key = self.class.insensitive_map[key.downcase] return get(key, context: context) end if self.class.[:allow_extra] return @contents[key] = self.class.value_attribute.load(value, context) if self.class.extra_keys.nil? extra_keys_key = self.class.extra_keys if @contents.key? extra_keys_key return @contents[extra_keys_key].get(key, context: context) end end raise LoadError, "Unknown key received: #{key.inspect} for #{Attributor.humanize_context(context)}" end |
#get_generic(key, context) ⇒ Object
354 355 356 357 358 359 360 361 362 363 364 365 366 |
# File 'lib/attributor/types/hash.rb', line 354 def get_generic(key, context) if @contents.key? key value = @contents[key] loaded_value = value_attribute.load(value, context) return self[key] = loaded_value elsif self.class.[:case_insensitive_load] key = key.downcase @contents.each do |k, _v| return get(key, context: context) if key == k.downcase end end nil end |
#key?(k) ⇒ Boolean Also known as: has_key?
577 578 579 |
# File 'lib/attributor/types/hash.rb', line 577 def key?(k) @contents.key?(k) end |
#key_attribute ⇒ Object
622 623 624 |
# File 'lib/attributor/types/hash.rb', line 622 def key_attribute self.class.key_attribute end |
#key_type ⇒ Object
614 615 616 |
# File 'lib/attributor/types/hash.rb', line 614 def key_type self.class.key_type end |
#keys ⇒ Object
565 566 567 |
# File 'lib/attributor/types/hash.rb', line 565 def keys @contents.keys end |
#merge(h) ⇒ Object
582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 |
# File 'lib/attributor/types/hash.rb', line 582 def merge(h) case h when self.class self.class.new(contents.merge(h.contents)) when Attributor::Hash source_key_type = self.class.key_type source_value_type = self.class.value_type # Allow merging hashes, but we'll need to coerce keys and/or values if they aren't the same type coerced_contents = h.contents.each_with_object({}) do |(key, val), object| k = (source_key_type && !k.is_a?(source_key_type)) ? source_key_type.load(key) : key v = (source_value_type && !k.is_a?(source_value_type)) ? source_value_type.load(val) : val object[k] = v end self.class.new(contents.merge(coerced_contents)) else raise TypeError, "no implicit conversion of #{h.class} into Attributor::Hash" end end |
#set(key, value, context: generate_subcontext(Attributor::DEFAULT_ROOT_CONTEXT, key), recurse: false) ⇒ Object
368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 |
# File 'lib/attributor/types/hash.rb', line 368 def set(key, value, context: generate_subcontext(Attributor::DEFAULT_ROOT_CONTEXT, key), recurse: false) key = self.class.key_attribute.load(key, context) if self.class.keys.empty? return self[key] = self.class.value_attribute.load(value, context) end if (attribute = self.class.keys[key]) return self[key] = attribute.load(value, context, recurse: recurse) end if self.class.[:case_insensitive_load] key = self.class.insensitive_map[key.downcase] return set(key, value, context: context) end if self.class.[:allow_extra] return self[key] = self.class.value_attribute.load(value, context) if self.class.extra_keys.nil? extra_keys_key = self.class.extra_keys unless @contents.key? extra_keys_key extra_keys_value = self.class.keys[extra_keys_key].load({}) @contents[extra_keys_key] = extra_keys_value end return self[extra_keys_key].set(key, value, context: context) end raise LoadError, "Unknown key received: #{key.inspect} while loading #{Attributor.humanize_context(context)}" end |
#size ⇒ Object
561 562 563 |
# File 'lib/attributor/types/hash.rb', line 561 def size @contents.size end |
#to_h ⇒ Object
315 316 317 |
# File 'lib/attributor/types/hash.rb', line 315 def to_h Attributor.recursive_to_h(@contents) end |
#validate(context = Attributor::DEFAULT_ROOT_CONTEXT) ⇒ Object
634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 |
# File 'lib/attributor/types/hash.rb', line 634 def validate(context = Attributor::DEFAULT_ROOT_CONTEXT) @validating = true context = [context] if context.is_a? ::String if self.class.keys.any? extra_keys = @contents.keys - self.class.keys.keys if extra_keys.any? && !self.class.[:allow_extra] return extra_keys.collect do |k| "#{Attributor.humanize_context(context)} can not have key: #{k.inspect}" end end self.validate_keys(context) else self.validate_generic(context) end ensure @validating = false end |
#validate_generic(context) ⇒ Object
687 688 689 690 691 692 693 694 695 696 697 698 699 700 |
# File 'lib/attributor/types/hash.rb', line 687 def validate_generic(context) @contents.each_with_object([]) do |(key, value), errors| # FIXME: the sub contexts and error messages don't really make sense here unless key_type == Attributor::Object sub_context = context + ["key(#{key.inspect})"] errors.concat key_attribute.validate(key, sub_context) end unless value_type == Attributor::Object sub_context = context + ["value(#{value.inspect})"] errors.concat value_attribute.validate(value, sub_context) end end end |
#validate_keys(context) ⇒ Object
653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 |
# File 'lib/attributor/types/hash.rb', line 653 def validate_keys(context) errors = [] keys_provided = [] self.class.keys.each do |key, attribute| sub_context = self.class.generate_subcontext(context, key) value = _get_attr(key) keys_provided << key if @contents.key?(key) if value.respond_to?(:validating) # really, it's a thing with sub-attributes next if value.validating end # Isn't this handled by the requirements validation? NO! we might want to combine if attribute.[:required] && !@contents.key?(key) errors.concat ["Attribute #{Attributor.humanize_context(sub_context)} is required."] end if @contents[key].nil? if !Attribute.nullable_attribute?(attribute.) && @contents.key?(key) errors.concat ["Attribute #{Attributor.humanize_context(sub_context)} is not nullable."] end # No need to validate the attribute further if the key wasn't passed...(or we would get nullable errors etc..cause the attribute has no # context if its containing key was even passed (and there might not be a containing key for a top level attribute anyways)) else errors.concat attribute.validate(value, sub_context) end end self.class.requirements.each do |requirement| validation_errors = requirement.validate(keys_provided, context) errors.concat(validation_errors) unless validation_errors.empty? end errors end |
#value_attribute ⇒ Object
626 627 628 |
# File 'lib/attributor/types/hash.rb', line 626 def value_attribute self.class.value_attribute end |
#value_type ⇒ Object
618 619 620 |
# File 'lib/attributor/types/hash.rb', line 618 def value_type self.class.value_type end |
#values ⇒ Object
569 570 571 |
# File 'lib/attributor/types/hash.rb', line 569 def values @contents.values end |