Class: Opto::Types::Enum

Inherits:
Opto::Type show all
Defined in:
lib/opto/types/enum.rb

Overview

A list of possible values

:options - a list of possible values for this enum :can_be_other - set to true if the value can be outside of the value list in options :in - when “can be other” is defined, this can be used to define an extra set of possible values

Examples:

Shorthand option list

Opto::Option.new(
  name: 'foo',
  type: 'enum',
  options:
    - foo
    - bar
    - cat
  can_be_other: true
)

Detailed option list

Opto::Option.new(
  name: 'foo',
  type: 'enum',
  options:
    - value: cat
      label: Cat
      description: A four legged ball of fur
    - value: dog
      label: Dog
      description: A friendly furry creature with a tail, says 'woof'
)

Constant Summary

Constants inherited from Opto::Type

Opto::Type::GLOBAL_OPTIONS

Instance Attribute Summary

Attributes inherited from Opto::Type

#options

Instance Method Summary collapse

Methods inherited from Opto::Type

#errors, for, inherited, #required?, #sanitize, sanitizer, sanitizers, true_when, #type, type, types, #valid?, #validate, validator, validators

Constructor Details

#initialize(options = {}) ⇒ Enum

Returns a new instance of Enum.



49
50
51
52
53
# File 'lib/opto/types/enum.rb', line 49

def initialize(options={})
  opts = normalize_opts(options.delete(:options))
  super(options)
  @options[:options] = opts
end

Instance Method Details

#normalize_opts(options) ⇒ Object



72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
# File 'lib/opto/types/enum.rb', line 72

def normalize_opts(options)
  case options
  when Hash
    options.each_with_object([]) do |(key, value), array|
      array << { value: key, label: key, description: value }
    end
  when ::Array
    case options.first
    when Hash
      options.each do |opt|
        if opt[:value].nil? || opt[:description].nil?
          raise TypeError, "Option definition requires value and description and can have label when using hash syntax"
        end
      end
      options
    when ::String, ( 0.class == Integer ? Integer : Fixnum )
      options.map do |opt|
        { value: opt, description: opt, label: opt }
      end
    when NilClass
      []
    else
      raise TypeError, "Invalid format for enum option list definition"
    end
  when NilClass
    []
  else
    raise TypeError, "Invalid format for enum option list definition"
  end
end