Created
December 1, 2009 11:58
-
-
Save stephanschubert/246244 to your computer and use it in GitHub Desktop.
Ruby module for convenient authenticity token generation and usage for any class
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
module AuthenticityToken | |
def authenticity_token(&block) | |
class_inheritable_accessor :authenticity_token_generator | |
self.authenticity_token_generator = block | |
include InstanceMethods | |
end | |
module InstanceMethods | |
def authenticity_token | |
block = self.class.authenticity_token_generator | |
instance_eval(&block) | |
end | |
def authenticity_token=(token) | |
# Does nothing, but avoids errors when used with | |
# a web framework like Rails which provides a | |
# mass-attribute-update-functionality. | |
end | |
def authentic?(token) | |
authenticity_token == token | |
end | |
end | |
end | |
# Usage example: | |
# | |
# class MyClass | |
# extend AuthenticityToken | |
# | |
# authenticity_token do | |
# Digest::MD5.hexdigest("bacon") | |
# end | |
# end | |
# | |
# my = MyClass.new | |
# my.authenticity_token # => "7813258ef8c6b632dde8cc80f6bda62f" | |
# my.authentic?("7813258ef8c6b632dde8cc80f6bda62f") # => true | |
# my.authentic?("wurst") # => false |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment