Class: NRSER::Types::IsA

Inherits:
Type
  • Object
show all
Defined in:
lib/nrser/types/is_a.rb

Direct Known Subclasses

ArrayType, HashType

Instance Attribute Summary collapse

Instance Method Summary collapse

Methods inherited from Type

#check, #from_s, #has_from_s?, #has_to_data?, #name, #respond_to?, short_name, #to_data, #to_s

Constructor Details

#initialize(klass, **options) ⇒ IsA

Returns a new instance of IsA.



9
10
11
12
13
14
15
16
17
18
19
20
21
# File 'lib/nrser/types/is_a.rb', line 9

def initialize klass, **options
  unless klass.is_a?( Class ) || klass.is_a?( Module )
    raise ArgumentError.new binding.erb <<-ERB
      `klass` argument must be a Class or Module, found:
      
          <%= klass.pretty_inspect %>
      
    ERB
  end
  
  super **options
  @klass = klass
end

Instance Attribute Details

#klassObject (readonly)

Returns the value of attribute klass.



7
8
9
# File 'lib/nrser/types/is_a.rb', line 7

def klass
  @klass
end

Instance Method Details

#default_nameObject



23
24
25
# File 'lib/nrser/types/is_a.rb', line 23

def default_name
  "#{ self.class.short_name }(#{ @klass.name })"
end

#from_data(data) ⇒ Object

If #klass responds to ‘#from_data`, call that and check results.

Otherwise, forward up to Type#from_data.

Parameters:

  • data (Object)

    Data to create the value from that will satisfy the type.

Returns:

  • (Object)

    Instance of #klass.



42
43
44
45
46
47
48
49
50
51
52
# File 'lib/nrser/types/is_a.rb', line 42

def from_data data
  if @from_data.nil?
    if @klass.respond_to? :from_data
      check @klass.from_data( data )
    else
      super data
    end
  else
    @from_data.call data
  end
end

#has_from_data?Boolean

Returns:

  • (Boolean)


55
56
57
# File 'lib/nrser/types/is_a.rb', line 55

def has_from_data?
  @from_data || @klass.respond_to?( :from_data )
end

#test(value) ⇒ Object



27
28
29
# File 'lib/nrser/types/is_a.rb', line 27

def test value
  value.is_a? @klass
end