Sha256: 34ebc8ab42bff10610e1cc441aa524d4184618ffa1d1f0b3f7bd8db79d538203

Contents?: true

Size: 931 Bytes

Versions: 13

Compression:

Stored size: 931 Bytes

Contents

module Rasti
  class Form
    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
end

Version data entries

13 entries across 13 versions & 1 rubygems

Version Path
rasti-form-3.1.2 lib/rasti/form/types/enum.rb
rasti-form-3.1.1 lib/rasti/form/types/enum.rb
rasti-form-3.1.0 lib/rasti/form/types/enum.rb
rasti-form-3.0.0 lib/rasti/form/types/enum.rb
rasti-form-2.2.0 lib/rasti/form/types/enum.rb
rasti-form-2.1.0 lib/rasti/form/types/enum.rb
rasti-form-2.0.0 lib/rasti/form/types/enum.rb
rasti-form-1.1.1 lib/rasti/form/types/enum.rb
rasti-form-1.1.0 lib/rasti/form/types/enum.rb
rasti-form-1.0.3 lib/rasti/form/types/enum.rb
rasti-form-1.0.2 lib/rasti/form/types/enum.rb
rasti-form-1.0.1 lib/rasti/form/types/enum.rb
rasti-form-1.0.0 lib/rasti/form/types/enum.rb