CookieMonster
CookieMonster is a Ruby library to work with HTTP Cookies. It allows to parse cookies from a HTTP header into an object and to convert the object back to a cookie string or response header.
Installation
Add this line to your application's Gemfile:
gem 'http_cookie_monster'
And then execute:
$ bundle
Or install it yourself as:
$ gem install http_cookie_monster
Usage
# include the gem into your code
#
require 'cookie_monster'
# a new cookie-monster object
#
= CookieMonster.new
# a new cookie-monster object with initial attributes
#
= CookieMonster.new({ :name => 'cookiename', :value => 'cookievalue', :httponly => true })
# a new cookie-monster object from a raw cookie HTTP request header
#
= CookieMonster.new 'Cookie: name=value; domain=.domain.com; path=/; httponly'
# a new cookie-monster object from a cookie string
#
= CookieMonster.new 'name=value; domain=.domain.com; path=/; httponly; secure'
#
# please note:
#
# name and value will be automatically URL decoded when parsed
# and automatically URL encoded when being set
#
# the following cookie attributes can be set
#
.name = 'myShinyCookie' # the name will be URL encoded
.value = 'test|123|zyx' # the value will be URL encoded as well
.path = '/'
.domain = '.my.domain.com'
.expires = Time.now + 7*86400 # must be a Time object
.httponly = true
.secure = true
# the attributes can be accessed like this
#
puts .name
puts .value
puts .path
puts .domain
puts .expires
puts .httponly
puts .secure
# there are some helper methods available
#
# is_valid? does some basic checks: is the cookie name set and is the expiry a Time object (if it's defined)
if .is_valid?
puts ":-)"
else
puts ":-("
end
# runs the validation and throws exceptions
#
.validate!
# sets the cookie expiry
#
.expires_in_seconds(60) # in 60 seconds
.expires_in_seconds(3600) # in 1 hour
.expires_in_seconds(86400) # in 1 day
.expires_in_seconds(-60) # expires the cookie
# expire cookies
#
.expire! # sets the expire date to a date in the past
.delete! # removes the cookie value
# export the cookie object - runs validate! and throws a RuntimeError exception if the cookie is invalid!
#
.to_s # convert to a string
.to_header # convert to a HTTP response header
# ... so this would be better
#
begin
puts .to_header
rescue => ex
puts "Failed to generate cookie: #{ex}"
end
Development
After checking out the repo, run bin/setup
to install dependencies. You can also run bin/console
for an interactive prompt that will allow you to experiment.
To install this gem onto your local machine, run bundle exec rake install
. To release a new version, update the version number in version.rb
, and then run bundle exec rake release
, which will create a git tag for the version, push git commits and tags, and push the .gem
file to rubygems.org.
Contributing
Bug reports and pull requests are welcome on GitHub at https://github.com/hirschnase/CookieMonster.
License
The gem is available as open source under the terms of the MIT License.