Class: UrlSigner
- Inherits:
-
Object
- Object
- UrlSigner
- Defined in:
- lib/url_signer.rb
Constant Summary collapse
- VERSION =
"0.2.0"
- DEFAULT_HASH_LENGTH =
10
- DEFAULT_SEPARATOR =
"_"
Instance Method Summary collapse
-
#initialize(secret, options = {}) ⇒ UrlSigner
constructor
Initialize new url-signer.
-
#sign(url) ⇒ Object
signs a given url.
-
#unsign(url) ⇒ Object
get url without hash (as it was before signing).
-
#valid?(url) ⇒ Boolean
validates a given URL.
Constructor Details
#initialize(secret, options = {}) ⇒ UrlSigner
Initialize new url-signer
Parameter
- secret (String)
-
secret for hashing
- options (Hash)
-
possible options are:
- :hash_length (Integer):: set length of hash
- :separator (String):: set separator for hash in url
21 22 23 24 25 |
# File 'lib/url_signer.rb', line 21 def initialize(secret, = {}) self.secret = secret self.hash_length = [:hash_length] || DEFAULT_HASH_LENGTH self.separator = [:separator] || DEFAULT_SEPARATOR end |
Instance Method Details
#sign(url) ⇒ Object
signs a given url
Parameter
- url (String)
-
whole URL to sign
Returns
signed URL (url with inserted hash)
35 36 37 38 39 |
# File 'lib/url_signer.rb', line 35 def sign(url) parsed_url = URI.parse(url) suffix = File.extname(parsed_url.path) parsed_url.to_s.gsub(/#{suffix}$/, "#{hash_with_separator(url)}#{suffix}") end |
#unsign(url) ⇒ Object
get url without hash (as it was before signing)
Parameter
- url (String)
-
url with inserted hash
Returns
Returns a URL without hash (as it was before signing)
48 49 50 51 52 53 54 55 56 |
# File 'lib/url_signer.rb', line 48 def unsign(url) parsed_url = URI.parse(url) suffix = File.extname(parsed_url.path) # extract hash with separator from uri url_without_suffix = parsed_url.to_s.gsub(/#{suffix}$/, "") url_without_hash_and_suffix = url_without_suffix.gsub(/#{separator}.{#{hash_length}}$/, "") unsigned_url = "#{url_without_hash_and_suffix}#{suffix}" return unsigned_url end |
#valid?(url) ⇒ Boolean
validates a given URL
Parameter
- url (String)
-
url to validate
Returns
true or false
65 66 67 |
# File 'lib/url_signer.rb', line 65 def valid?(url) hash(unsign(url)) == extract_hash(url) end |