Class: Divshare::Encoder
- Inherits:
-
Object
- Object
- Divshare::Encoder
- Defined in:
- lib/divshare/encoder.rb
Overview
Manages the arguments send along with a POST to the DivShare API URL. Takes care of organizing arguments and generating API signatures for requests
Instance Attribute Summary collapse
-
#key ⇒ Object
readonly
:nodoc:.
-
#secret ⇒ Object
readonly
:nodoc:.
-
#session_key ⇒ Object
Returns the value of attribute session_key.
Instance Method Summary collapse
-
#encode(method, args = {}) ⇒ Object
Prepares arguments for a post using the given method and arguments.
-
#initialize(key, secret) ⇒ Encoder
constructor
A new instance of Encoder.
-
#sign(args) ⇒ Object
Generates the required MD5 signature as described in www.divshare.com/integrate/api#sig.
- #string_to_sign(args) ⇒ Object
Constructor Details
#initialize(key, secret) ⇒ Encoder
Returns a new instance of Encoder.
10 11 12 |
# File 'lib/divshare/encoder.rb', line 10 def initialize(key, secret) @key, @secret = key, secret end |
Instance Attribute Details
#key ⇒ Object (readonly)
:nodoc:
7 8 9 |
# File 'lib/divshare/encoder.rb', line 7 def key @key end |
#secret ⇒ Object (readonly)
:nodoc:
7 8 9 |
# File 'lib/divshare/encoder.rb', line 7 def secret @secret end |
#session_key ⇒ Object
Returns the value of attribute session_key.
8 9 10 |
# File 'lib/divshare/encoder.rb', line 8 def session_key @session_key end |
Instance Method Details
#encode(method, args = {}) ⇒ Object
Prepares arguments for a post using the given method and arguments. Returns a hash of arguments and values
16 17 18 19 20 21 22 23 24 25 26 |
# File 'lib/divshare/encoder.rb', line 16 def encode(method, args={}) # Stringifies incoming keys and values post_args = Hash.new args.each { |k, v| post_args[k.to_s] = v.to_s } post_args.merge!({'method' => method.to_s, 'api_key' => @key.to_s}) if @session_key sig = sign(post_args) post_args.merge!({'api_session_key' => @session_key.to_s, 'api_sig' => sig}) end post_args end |
#sign(args) ⇒ Object
Generates the required MD5 signature as described in www.divshare.com/integrate/api#sig
30 31 32 |
# File 'lib/divshare/encoder.rb', line 30 def sign(args) Digest::MD5.hexdigest(string_to_sign(args)) end |
#string_to_sign(args) ⇒ Object
From www.divshare.com/integrate/api
-
Your secret key is 123-secret.
-
Your session key is 456-session.
-
You are using the get_user_files method, and you’re sending the parameters limit=5 and offset=10.
The string used to create your signature will be: 123-secret456-sessionlimit5offset10. Note that the parameters must be in alphabetical order, so limit always comes before offset. Each parameter should be paired with its value as shown.
45 46 47 48 |
# File 'lib/divshare/encoder.rb', line 45 def string_to_sign(args) args_for_string = args.dup.delete_if {|k,v| %w(api_key method api_sig api_session_key).include?(k) } "#{@secret}#{@session_key}#{args_for_string.to_a.sort.flatten.join}" end |