Sha256: b27122499a3008b31e59a37b938806f00d00947d391980538edd7a8ee5131ceb

Contents?: true

Size: 844 Bytes

Versions: 1

Compression:

Stored size: 844 Bytes

Contents

module Rasti
  module Types
    class Enum

      include Castable

      attr_reader :values

      def self.[](*values)
        new values
      end

      def to_s
        "#{self.class}[#{values.map(&:inspect).join(', ')}]"
      end
      alias_method :inspect, :to_s

      private

      def initialize(values)
        @values = values.map(&:to_s)
        define_getters
      end

      def valid?(value)
        values.include? String.cast(value)
      rescue
        false
      end

      def transform(value)
        String.cast value
      end

      def define_getters
        values.each do |value|
          getter_name = value.gsub(/([A-Z]+)([A-Z][a-z])/, '\1_\2').gsub(/([a-z])([A-Z])/, '\1_\2').downcase
          define_singleton_method getter_name do
            value
          end
        end
      end

    end
  end
end

Version data entries

1 entries across 1 versions & 1 rubygems

Version Path
rasti-types-1.0.0 lib/rasti/types/enum.rb