Class: Jimmu::CookieJar

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

Overview

Read/write access to request and response cookies for a single request. cookie[:user] reads an incoming cookie value (or nil). cookie[:user] = "value" queues a Set-Cookie header on the response. Values are transparently percent-encoded/decoded so any text (including Japanese) round-trips safely.

Instance Method Summary collapse

Constructor Details

#initialize(cookie_header) ⇒ CookieJar

Returns a new instance of CookieJar.



581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
# File 'lib/jimmu.rb', line 581

def initialize(cookie_header)
  @incoming = {}
  cookie_header.to_s.split(';').each do |pair|
    k, v = pair.split('=', 2)
    next unless k
    k = k.strip
    next if k.empty?
    v = (v || '').strip
    @incoming[k] = begin
      URI.decode_www_form_component(v)
    rescue ArgumentError
      v
    end
  end
  @outgoing = []
end

Instance Method Details

#[](name) ⇒ Object



598
599
600
# File 'lib/jimmu.rb', line 598

def [](name)
  @incoming[name.to_s]
end

#[]=(name, value) ⇒ Object



602
603
604
# File 'lib/jimmu.rb', line 602

def []=(name, value)
  set(name, value)
end

#delete(name, path: '/') ⇒ Object



619
620
621
# File 'lib/jimmu.rb', line 619

def delete(name, path: '/')
  set(name, '', path: path, max_age: 0, expires: Time.at(0))
end

#response_header_valuesObject



627
628
629
# File 'lib/jimmu.rb', line 627

def response_header_values
  @outgoing
end

#set(name, value, path: '/', max_age: nil, expires: nil, http_only: false, secure: false, same_site: nil) ⇒ Object

Full control over cookie attributes when needed.



607
608
609
610
611
612
613
614
615
616
617
# File 'lib/jimmu.rb', line 607

def set(name, value, path: '/', max_age: nil, expires: nil, http_only: false, secure: false, same_site: nil)
  parts = ["#{name}=#{URI.encode_www_form_component(value.to_s)}"]
  parts << "Path=#{path}" if path
  parts << "Max-Age=#{max_age.to_i}" if max_age
  parts << "Expires=#{expires.httpdate}" if expires
  parts << 'HttpOnly' if http_only
  parts << 'Secure' if secure
  parts << "SameSite=#{same_site}" if same_site
  @outgoing << parts.join('; ')
  value
end

#to_aObject



623
624
625
# File 'lib/jimmu.rb', line 623

def to_a
  @incoming.dup
end