Sha256: 65280a78daf735639c32dcf030ead97027f03484551f3a60a3decbea190c5c06

Contents?: true

Size: 1.21 KB

Versions: 1

Compression:

Stored size: 1.21 KB

Contents

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 = get_option_value(self.class.refcode_options[:secret])
        r.salt = get_option_value(self.class.refcode_options[:salt])
        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

    def get_option_value option
      if option.respond_to? :call
        option.call self
      elsif option.is_a? Symbol
        self.send option
      else
        option
      end
    end

  end

end

Version data entries

1 entries across 1 versions & 1 rubygems

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