Sha256: 2f1abb4ce1c101d8ea690c4446f42b7726dddfeef628b45615dcbe73944a9f16

Contents?: true

Size: 1.34 KB

Versions: 1

Compression:

Stored size: 1.34 KB

Contents

require "env_compat/version"

module EnvCompat
  class << self
    def encode str
      builder = ''
      _ = CodeBlock.new
      str.chars.each do |chr|
        case chr
        when *mapping.values
          builder = _.toggle(builder) unless _.in_block?
          builder << mapping.invert[chr]
        else
          builder = _.toggle(builder) if _.in_block?
          builder << chr
        end
      end
      builder.upcase
    end

    def decode str
      builder = ''
      _ = CodeBlock.new
      str.chars.each do |chr|
        next _.cycle if chr == '_'
        if _.in_block?
          case chr
          when *mapping.keys
            builder << mapping[chr]
          else
            raise "Invalid input!"
          end
        else
          builder << chr
        end
      end
      builder.upcase
    end

    private
    def mapping
      {
        'F' => '/', # Forward Slash
        'C' => ':', # Colon
        'M' => '-', # Minus
        'U' => '_', # Underscore
        'D' => '.'  # Dot
      }
    end

    class CodeBlock
      def initialize
        @code_block = [false, true].cycle
      end
       
      def cycle
        @code_block.next
      end

      def in_block?
        @code_block.peek
      end

      def toggle str
        @code_block.next
        str + '_'
      end
    end 
    private_constant :CodeBlock
  end
end

Version data entries

1 entries across 1 versions & 1 rubygems

Version Path
env_compat-0.1.0 lib/env_compat.rb