Sha256: f2991dca567f9b64cada3ebd9ac421923336d854849a19382ea1c6df414a8876

Contents?: true

Size: 1.04 KB

Versions: 1

Compression:

Stored size: 1.04 KB

Contents

module Refcode

  module Encodable

    def self.included base
      base.extend ClassMethods
    end

    def generate_refcode val
      raise 'You must call the has_refcode method in your class definition' unless self.class.refcode_options
      encoder.encode val
    end

    def parse_refcode code
      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|
        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
        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

  end

end

Version data entries

1 entries across 1 versions & 1 rubygems

Version Path
refcode-0.1.0 lib/refcode/encodable.rb