Class: Watir::Cookies

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

Instance Method Summary collapse

Constructor Details

#initialize(control) ⇒ Cookies

Returns a new instance of Cookies.


7
8
9
# File 'lib/watir/cookies.rb', line 7

def initialize(control)
  @control = control
end

Instance Method Details

#[](name) ⇒ Hash

Returns a cookie by name.

Examples:

browser.cookies[:my_session]
#=> {:name=>"my_session", :value=>"BAh7B0kiD3Nlc3Npb25faWQGOgZFRkk", :domain=>"mysite.com"}

Parameters:

Returns:

  • (Hash)

    or nil if not found


38
39
40
# File 'lib/watir/cookies.rb', line 38

def [](name)
  to_a.find { |c| c[:name] == name.to_s }
end

#add(name, value, opts = {}) ⇒ Object

Adds new cookie.

Examples:

browser.cookies.add 'my_session', 'BAh7B0kiD3Nlc3Npb25faWQGOgZFRkk', secure: true

Parameters:

  • name (String)
  • value (String)
  • opts (Hash) (defaults to: {})

Options Hash (opts):

  • :secure (Boolean)
  • :path (String)
  • :expires (Time, DateTime, NilClass)
  • :domain (String)

57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
# File 'lib/watir/cookies.rb', line 57

def add(name, value, opts = {})
  cookie = {
    name: name,
    value: value
  }
  cookie[:secure] = opts[:secure] if opts.key?(:secure)
  cookie[:path] = opts[:path] if opts.key?(:path)
  expires = opts[:expires]
  if expires
    cookie[:expires] = expires.is_a?(String) ? ::Time.parse(expires) : expires
  end
  cookie[:domain] = opts[:domain] if opts.key?(:domain)

  @control.add_cookie cookie
end

#clearObject

Deletes all cookies.

Examples:

browser.cookies.clear

93
94
95
# File 'lib/watir/cookies.rb', line 93

def clear
  @control.delete_all_cookies
end

#delete(name) ⇒ Object

Deletes cookie by given name.

Examples:

browser.cookies.delete 'my_session'

Parameters:

  • name (String)

82
83
84
# File 'lib/watir/cookies.rb', line 82

def delete(name)
  @control.delete_cookie(name)
end

#load(file = '.cookies') ⇒ Object

Load cookies from file

Examples:

browser.cookies.load '.cookies'

Parameters:

  • file (String) (defaults to: '.cookies')

119
120
121
122
123
# File 'lib/watir/cookies.rb', line 119

def load(file = '.cookies')
  YAML.safe_load(File.read(file), permitted_classes: [::Symbol, ::Time]).each do |c|
    add(c.delete(:name), c.delete(:value), c)
  end
end

#save(file = '.cookies') ⇒ Object

Save cookies to file

Examples:

browser.cookies.save '.cookies'

Parameters:

  • file (String) (defaults to: '.cookies')

106
107
108
# File 'lib/watir/cookies.rb', line 106

def save(file = '.cookies')
  File.write(file, to_a.to_yaml)
end

#to_aArray<Hash>

Returns array of cookies.

Examples:

browser.cookies.to_a
#=> {:name=>"my_session", :value=>"BAh7B0kiD3Nlc3Npb25faWQGOgZFRkk", :domain=>"mysite.com"}

Returns:

  • (Array<Hash>)

21
22
23
24
25
# File 'lib/watir/cookies.rb', line 21

def to_a
  @control.all_cookies.map do |e|
    e.merge(expires: e[:expires]&.to_time)
  end
end