lib/defender/document.rb in defender-1.0.0beta1 vs lib/defender/document.rb in defender-1.0.0
- old
+ new
@@ -1,6 +1,9 @@
module Defender
+ ##
+ # A document contains data to be analyzed by Defensio, or that has been
+ # analyzed.
class Document
##
# Whether the document should be published on your Web site or not.
#
# For example, spam and malicious content are not allowed.
@@ -36,19 +39,23 @@
# Please note that this only retrieves the status of the document (like
# it's spaminess, whether it should be allowed or not, etc.) and not the
# content of the request (all of the data in the {#data} hash).
#
# @param [String] signature The signature of the document to retrieve
- # @return [Document] The document to retrieve
+ # @return [Document,nil] The document to retrieve, or nil
def self.find(signature)
document = new
- _code, data = Defender.defensio.get_document(signature)
- document.instance_variable_set(:@saved, true)
- document.instance_variable_set(:@allow, data['allow'])
- document.instance_variable_set(:@signature, signature)
+ ret = Defender.call(:get_document, signature)
+ if ret
+ document.instance_variable_set(:@saved, true)
+ document.instance_variable_set(:@allow, ret.last['allow'])
+ document.instance_variable_set(:@signature, signature)
- document
+ document
+ else
+ nil
+ end
end
##
# Initializes a new document
def initialize
@@ -69,21 +76,41 @@
# before. If it has been saved, it will submit whether the document was a
# false positive/negative (set the {#allow} param before saving to do
# this).
#
# @see #saved?
+ # @return [Boolean] Whether the save succeded or not.
def save
if saved?
- _code, data = Defender.defensio.put_document(@signature, {:allow => @allow})
+ ret = Defender.call(:put_document, @signature, {:allow => @allow})
else
- data = {}
- @data.each { |k,v|
- data[k.to_s.gsub('_','-')] = v.to_s
- }
- _code, data = Defender.defensio.post_document(@data)
- @allow = data['allow']
- @signature = data['signature']
- @saved = true
+ ret = Defender.call(:post_document, self.class.normalize_data(@data))
end
+ return false if ret == false
+ return true if saved?
+
+ data = ret.last
+ @allow = data['allow']
+ @signature = data['signature']
+
+ @saved = true # This will also return true, since nothing failed as we got here
+ end
+
+
+ ##
+ # Normalizes a data hash to submit to defensio.
+ #
+ # @param [Hash] hsh The hash to be normalized
+ # @return [Hash{String => String}] The normalized hash
+ def self.normalize_data(data)
+ normalized = {}
+ data.each { |key, value|
+ if value.respond_to?(:strftime)
+ value = value.strftime('%Y-%m-%d')
+ end
+ normalized[key.to_s.gsub('_','-')] = value.to_s
+ }
+
+ normalized
end
end
end