Class: Greed::Cookie::Parser

Inherits:
Object
  • Object
show all
Defined in:
lib/greed/cookie/parser.rb

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(cookie_matcher: nil, attribute_matcher: nil, flag_matcher: nil) ⇒ Parser

Returns a new instance of Parser.



21
22
23
24
25
26
27
28
29
30
# File 'lib/greed/cookie/parser.rb', line 21

def initialize(\
  cookie_matcher: nil,
  attribute_matcher: nil,
  flag_matcher: nil
)
  @cookie_matcher = cookie_matcher || self.class._default_kv_matcher
  @attribute_matcher = attribute_matcher || self.class._default_kv_matcher
  @flag_matcher = flag_matcher || self.class._default_flag_matcher
  freeze
end

Class Method Details

._default_flag_matcherObject



16
17
18
# File 'lib/greed/cookie/parser.rb', line 16

def _default_flag_matcher
  @__default_flag_matcher ||= /\A\s*([-_\w\d]+)\s*(?:;\s*|\z)/
end

._default_kv_matcherObject



12
13
14
# File 'lib/greed/cookie/parser.rb', line 12

def _default_kv_matcher
  @__default_kv_matcher ||= /\A\s*([-_.+%\d\w]+)=\s*([^;]*)\s*(?:;\s*|\z)/
end

Instance Method Details

#parse(set_cookie_header) ⇒ Object



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
60
61
62
63
64
65
66
67
68
69
# File 'lib/greed/cookie/parser.rb', line 32

def parse(set_cookie_header)
  scanner = ::StringScanner.new(set_cookie_header)
  matched = scanner.scan(@cookie_matcher)
  return nil unless matched
  captured = scanner.captures
  mandatory_parsed = {
    name: captured[0].tap do |cookie_name|
      return nil unless cookie_name.present?
    end,
    value: captured[1],
  }
  flags_parsed = {}
  attributes_parsed = {}
  until scanner.eos? do
    matched = scanner.scan(@flag_matcher)
    if matched
      captured = scanner.captures
      flags_parsed.merge!(
        "#{captured[0].downcase}": true,
      )
      next
    end
    matched = scanner.scan(@attribute_matcher)
    if matched
      captured = scanner.captures
      attributes_parsed.merge!(
        "#{captured[0].downcase}": captured[1],
      )
      next
    end
    return nil
  end
  combine_fragments(
    mandatory_parsed,
    attributes_parsed,
    flags_parsed
  )
end