module Refcode module Encodable def self.included base base.extend ClassMethods end def generate_refcode val check_refcode_options! encoder.encode val end def parse_refcode code check_refcode_options! encoder.decode code end module ClassMethods def has_refcode options raise ArgumentError unless options[:secret] && options[:salt] @refcode_options = options end def refcode_options @refcode_options end end private def encoder Refcode::Encoder.new do |r| check_refcode_options! r.secret = self.class.refcode_options[:secret] salt_option = self.class.refcode_options[:salt] if salt_option.respond_to? :call r.salt = salt_option.call self elsif salt_option.is_a? Symbol r.salt = self.send salt_option else r.salt = salt_option end raise "Value for salt is nil (#{salt_option} given)" if r.salt.nil? end end def check_refcode_options! raise RefcodeInitException.new('You must call the has_refcode method in your class definition') unless self.class.refcode_options end end end