Sha256: 34620c81071b2b373f7d710832b0f0fd284060cc94218df3db37faeea6926370

Contents?: true

Size: 1.11 KB

Versions: 2

Compression:

Stored size: 1.11 KB

Contents

require 'sitehub/cookie'
require 'sitehub/constants'
class SiteHub

  module CookieRewriting

    ENDING_WITH_NEWLINE = /#{NEW_LINE}$/

    def rewrite_cookies(headers, substitute_domain:)
      cookies_hash = cookies_string_as_hash(headers[Constants::HttpHeaderKeys::SET_COOKIE])

      cookies_hash.values.each do |cookie|
        if domain_attribute = cookie.find(:domain)
          value = domain_attribute.value
          domain_attribute.value = substitute_domain.dup
          domain_attribute.value.prepend(FULL_STOP) if value.start_with?(FULL_STOP)
        end
      end
      headers[HttpHeaders::SET_COOKIE] = cookies_hash_to_string(cookies_hash)
    end

    def cookies_hash_to_string cookies_hash
      cookies_hash.values.inject(EMPTY_STRING.dup) do |cookie_string, cookie|
        cookie_string << "#{cookie.to_s}#{NEW_LINE}"
      end.sub(ENDING_WITH_NEWLINE, EMPTY_STRING)
    end

    def cookies_string_as_hash cookie_string
      cookie_string.lines.inject({}) do |cookies, cookie_line|
        cookie = SiteHub::Cookie.new(cookie_line)
        cookies[cookie.name] = cookie; cookies
      end
    end
  end
end

Version data entries

2 entries across 2 versions & 1 rubygems

Version Path
sitehub-0.4.2 lib/sitehub/cookie_rewriting.rb
sitehub-0.4.1 lib/sitehub/cookie_rewriting.rb