Module: EnumEnforcer
- Included in:
- SchwabRb::BaseClient, SchwabRb::Orders::Builder
- Defined in:
- lib/schwab_rb/utils/enum_enforcer.rb
Instance Method Summary collapse
- #convert_enum(value, enum_type) ⇒ Object
- #convert_enum_iterable(iterable, enum_type) ⇒ Object
- #enforce_enums=(value) ⇒ Object
- #enforce_enums? ⇒ Boolean
- #get_valid_enum_values(enum_type) ⇒ Object
- #set_enforce_enums(enforce_enums) ⇒ Object
- #type_error(value, required_enum_type) ⇒ Object
Instance Method Details
#convert_enum(value, enum_type) ⇒ Object
30 31 32 33 34 35 36 37 38 39 40 41 42 |
# File 'lib/schwab_rb/utils/enum_enforcer.rb', line 30 def convert_enum(value, enum_type) return nil if value.nil? valid_values = enum_type.constants.map { |const| enum_type.const_get(const) } if valid_values.include? value value elsif enforce_enums type_error(value, enum_type) else value end end |
#convert_enum_iterable(iterable, enum_type) ⇒ Object
44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 |
# File 'lib/schwab_rb/utils/enum_enforcer.rb', line 44 def convert_enum_iterable(iterable, enum_type) return [] if iterable.nil? valid_values = get_valid_enum_values(enum_type) return [iterable] if valid_values.include? iterable values = [] iterable.each do |value| if valid_values.include? value values << value elsif enforce_enums type_error(value, enum_type) else values << value end end values end |
#enforce_enums=(value) ⇒ Object
8 9 10 |
# File 'lib/schwab_rb/utils/enum_enforcer.rb', line 8 def enforce_enums=(value) @enforce_enums = value end |
#enforce_enums? ⇒ Boolean
4 5 6 |
# File 'lib/schwab_rb/utils/enum_enforcer.rb', line 4 def enforce_enums? @enforce_enums ||= false end |
#get_valid_enum_values(enum_type) ⇒ Object
69 70 71 |
# File 'lib/schwab_rb/utils/enum_enforcer.rb', line 69 def get_valid_enum_values(enum_type) enum_type.constants.map { |const| enum_type.const_get(const) } end |
#set_enforce_enums(enforce_enums) ⇒ Object
65 66 67 |
# File 'lib/schwab_rb/utils/enum_enforcer.rb', line 65 def set_enforce_enums(enforce_enums) @enforce_enums = enforce_enums end |
#type_error(value, required_enum_type) ⇒ Object
12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 |
# File 'lib/schwab_rb/utils/enum_enforcer.rb', line 12 def type_error(value, required_enum_type) = "" if value.is_a? String possible_members = required_enum_type.constants.filter_map do |member| fullname = "#{required_enum_type}::#{member}" fullname if fullname.include?(value) end if possible_members.any? = "Did you mean #{possible_members[0..-2].join(', ')}#{possible_members.size > 1 ? ' or ' : ''}#{possible_members[-1]}? " end end raise ArgumentError, "expected type \"#{required_enum_type}\", got type \"#{value.class}\". #{possible_members_message}(initialize with enforce_enums: false to disable this checking)" end |