Class: RiderServer::Validate::Symbol

Inherits:
Base show all
Defined in:
lib/rider_server/validate/symbol.rb

Instance Method Summary collapse

Methods inherited from Base

#fail, validate

Methods included from PredicateLogic

#add_predicate, #check_predicates

Instance Method Details

#default(value) ⇒ Object



15
16
17
18
# File 'lib/rider_server/validate/symbol.rb', line 15

def default(value)
  @default = value
  self
end

#emptyObject

Require that the input be empty.



35
36
37
38
39
40
# File 'lib/rider_server/validate/symbol.rb', line 35

def empty
  add_predicate do |data|
    [data.empty?, "must be empty"]
  end
  self
end

#not_emptyObject

Require that the input be not empty.



43
44
45
46
47
48
# File 'lib/rider_server/validate/symbol.rb', line 43

def not_empty
  add_predicate do |data|
    [!data.empty?, "must not be empty"]
  end
  self
end

#one_of(*values) ⇒ Object

Require that the input be one of the values.

Raises:

  • (ArgumentError)


21
22
23
24
25
26
27
28
29
30
31
32
# File 'lib/rider_server/validate/symbol.rb', line 21

def one_of(*values)
  raise ArgumentError, "one_of requires at least one value" if values.empty?
  values.each do |value|
    raise ArgumentError, "one_of requires all values to be symbols but #{value.inspect} is not" \
      unless value.is_a?(::Symbol)
  end

  add_predicate do |data|
    [values.member?(data), "must one of #{values.inspect}"]
  end
  self
end

#upcaseObject

Convert the input to an upcase version if possible.



51
52
53
54
# File 'lib/rider_server/validate/symbol.rb', line 51

def upcase
  @upcase = true
  self
end

#validate(data, loc = "") ⇒ Object



56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
# File 'lib/rider_server/validate/symbol.rb', line 56

def validate(data, loc = "")
  if data.nil? && @default
    data = @default
  elsif data.nil?
    fail(data, loc, "no default value set")
  end

  if data.respond_to?(:upcase)
    begin
      data = data.upcase if @upcase
    rescue
      fail(data, loc, "can't upcase symbol")
    end
  end

  begin
    data = data.to_sym
  rescue
    fail(data, loc, "can't convert to a symbol")
  end

  result, reason = check_predicates(data)
  unless result
    fail(data, loc, reason)
  end

  data
end