Class: Clive::Type

Inherits:
Object
  • Object
show all
Defined in:
lib/clive/type.rb,
lib/clive/type/lookup.rb,
lib/clive/type/definitions.rb

Direct Known Subclasses

Object

Defined Under Namespace

Modules: Lookup Classes: Array, Binary, Boolean, Float, Hexadecimal, Integer, Object, Octal, Pathname, Range, Regexp, StrictInteger, String, Symbol, Time

Class Method Summary collapse

Instance Method Summary collapse

Class Method Details

.cast(sym, *args) ⇒ Object

Shorthand to define a method which is called on the string argument to return the correct type.

Examples:


class Symbol < Type
  # ...
  cast :to_sym
end

Parameters:

  • sym (::Symbol)

82
83
84
# File 'lib/clive/type.rb', line 82

def cast(sym, *args)
  @cast = [sym, args]
end

.find_class(name) ⇒ Object

Find the class for name.

Parameters:


18
19
20
21
# File 'lib/clive/type.rb', line 18

def find_class(name)
  name = name.split('::').last
  Clive::Type.const_get(name) if Clive::Type.const_defined?(name)
end

.match(other) ⇒ Object

Shorthand to define #valid? for subclasses of Clive::Type, pass a regular expression that should be matched or a symbol for a method which will be called on the argument that returns either true (valid) or false (invalid).

Examples:

With a regular expression


class YesNo < Type
  match /yes|no/
  # ...
end

With a method symbol


class String
  def five?
    size == 5
  end
end

class FiveChars < Type
  match :five?
  # ...
end

Parameters:

  • other (#to_proc, ::Regexp)

50
51
52
53
54
55
56
# File 'lib/clive/type.rb', line 50

def match(other)
  if other.respond_to?(:to_proc)
    @valid = other.to_proc
  else
    @valid = proc {|arg| other =~ arg.to_s }
  end
end

.refute(other) ⇒ Object

Similar to match but opposite, so where match would be valid refute is invalid.

Parameters:

  • other (#to_proc, ::Regexp)

62
63
64
65
66
67
68
# File 'lib/clive/type.rb', line 62

def refute(other)
  if other.respond_to?(:to_proc)
    @valid = proc {|arg| !arg.send(other) }
  else
    @valid = proc {|arg| other !~ arg.to_s }
  end
end

.typecast(arg) ⇒ Object

Casts the arg to the correct type, if cast has been called it uses the proc created otherwise it calls #typecast.

Parameters:


103
104
105
106
107
108
109
# File 'lib/clive/type.rb', line 103

def typecast(arg)
  if @cast
    arg.send @cast[0], *@cast[1]
  else
    new.typecast arg
  end
end

.valid?(arg) ⇒ Boolean

Checks whether the arg passed is valid, if match or refute have been called it uses the Proc created by them otherwise calls #valid?.

Parameters:

Returns:


91
92
93
94
95
96
97
# File 'lib/clive/type.rb', line 91

def valid?(arg)
  if @valid
    @valid.call arg
  else
    new.valid? arg
  end
end

Instance Method Details

#typecast(arg) ⇒ Object

Parameters:


10
11
12
# File 'lib/clive/type.rb', line 10

def typecast(arg)
  nil
end

#valid?(arg) ⇒ Boolean

Parameters:

Returns:


5
6
7
# File 'lib/clive/type.rb', line 5

def valid?(arg)
  false
end