Sha256: 1d2fb8e1803bac535be4eb4b836e8c32c3b1935633fc344ff905445eafaeca56

Contents?: true

Size: 1.92 KB

Versions: 2

Compression:

Stored size: 1.92 KB

Contents

# encoding: utf-8
#
require 'mode/sdk/hash_util'
require 'mode/sdk/warehouse_util'

module Mode
  module Sdk
    # Represents a single column of a table stored in the Mode public data
    # warehouse
    #
    # @attr [Hash] attributes hash of column attributes
    #
    class Column
      extend Mode::Sdk::WarehouseUtil
      include Mode::Sdk::HashUtil

      attr_reader :attributes

      # Construct a new Column instance
      #
      # @param attributes [Hash] hash of column attributes
      #
      # @return [Mode::Sdk::Column] the instance
      #
      def initialize(attributes)
        @attributes = stringify_keys(attributes)
      end

      # Validate the provided column attributes
      #
      # @return [true]
      #
      def validate!
        validate_keys!
        validate_name!
        validate_type!

        true
      end

      private

      KEYS  = %w(name type)
      TYPES = %w(serial string integer number date time datetime boolean)

      NAME_PATTERN = /\A[a-z][a-z0-9_]{0,62}[a-z0-9]\z/

      def name
        attributes.fetch('name').to_s
      end

      def type
        attributes.fetch('type').to_s
      end

      def keys
        attributes.keys
      end

      def validate_keys!
        KEYS.each do |key|
          next if keys.include?(key)

          invalid! "Column missing required key '#{key}': #{attributes.inspect}"
        end

        extra = keys - KEYS

        invalid! "Column has unexpected keys: #{extra.inspect}" if extra.any?

        true
      end

      def validate_name!
        invalid! "Column name is invalid: #{name}" unless name =~ NAME_PATTERN

        true
      end

      def validate_type!
        unless TYPES.include?(type)
          invalid! "Column type is invalid: #{type} (valid: #{TYPES.inspect})"
        end

        true
      end

      def invalid!(message)
        fail InvalidError, message
      end

      class InvalidError < StandardError; end
    end
  end
end

Version data entries

2 entries across 2 versions & 1 rubygems

Version Path
mode-sdk-0.1.0 lib/mode/sdk/column.rb
mode-sdk-0.0.1 lib/mode/sdk/column.rb