Class: Dommy::Headers

Inherits:
Object
  • Object
show all
Defined in:
lib/dommy/fetch.rb

Overview

Minimal ‘Headers` proxy. Consumer code typically calls `headers.call(:entries)` and iterates via `Array.from(…)`, so we just need `entries` and `get`.

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(hash) ⇒ Headers

Returns a new instance of Headers.



261
262
263
# File 'lib/dommy/fetch.rb', line 261

def initialize(hash)
  @hash = hash.is_a?(Hash) ? hash.transform_keys(&:to_s) : {}
end

Class Method Details

.canonical(name) ⇒ Object



307
308
309
# File 'lib/dommy/fetch.rb', line 307

def self.canonical(name)
  name.split("-").map(&:capitalize).join("-")
end

Instance Method Details

#__js_call__(method, args) ⇒ Object



277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
# File 'lib/dommy/fetch.rb', line 277

def __js_call__(method, args)
  case method
  when "get"
    name = args[0].to_s
    @hash[name] || @hash[Headers.canonical(name)]
  when "entries"
    @hash.to_a
  when "has"
    # Match `get`'s case-insensitive lookup: try the raw name
    # first, then the Title-Case canonical form. WHATWG defines
    # header names as case-insensitive throughout the Headers API.
    name = args[0].to_s
    @hash.key?(name) || @hash.key?(Headers.canonical(name))
  when "forEach"
    # WHATWG: forEach(callback) — callback(value, key, headers).
    # Pass `self` as the third argument so consumers that read
    # `(_, _, h) => h.get("Foo")` work the same as in a browser.
    cb = args[0]
    @hash.each do |k, v|
      if cb.respond_to?(:__js_call__)
        cb.__js_call__("call", [v, k, self])
      elsif cb.respond_to?(:call)
        cb.call(v, k, self)
      end
    end

    nil
  end
end

#__js_get__(_key) ⇒ Object



269
270
271
# File 'lib/dommy/fetch.rb', line 269

def __js_get__(_key)
  nil
end

#__js_set__(_key, _value) ⇒ Object



273
274
275
# File 'lib/dommy/fetch.rb', line 273

def __js_set__(_key, _value)
  nil
end

#to_hObject



265
266
267
# File 'lib/dommy/fetch.rb', line 265

def to_h
  @hash.dup
end