Class: TreeStruct::Attribute

Inherits:
Object
  • Object
show all
Defined in:
lib/tree_struct/attribute.rb

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(name, array: false, class: nil, default: nil, parent:, &block) ⇒ Attribute

Returns a new instance of Attribute.

Raises:

  • (ArgumentError)


7
8
9
10
11
12
13
14
15
16
17
# File 'lib/tree_struct/attribute.rb', line 7

def initialize(name, array: false, class: nil, default: nil, parent:, &block)
  @name = name.to_sym
  @array = array
  @default_value = default
  @parent = parent

  @nested_class = binding.local_variable_get(:class)
  @nested_class = Class.new(@parent.nested_class, &block) if !@nested_class && block_given?

  raise ArgumentError.new('Nested structure has to be defined (either with :class parameter or with block) for arrays if :default parameter is not specified') if @array && @nested_class.nil? && @default_value.nil?
end

Instance Attribute Details

#nameObject (readonly)

Returns the value of attribute name.



5
6
7
# File 'lib/tree_struct/attribute.rb', line 5

def name
  @name
end

Instance Method Details

#default_valueObject



41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
# File 'lib/tree_struct/attribute.rb', line 41

def default_value
  if @default_value.nil?
    if @nested_class
      if @array
        create_array
      else
        create_nested
      end
    end

  elsif @default_value.is_a? Proc
    @default_value.call(@parent, self)

  else
    @default_value
  end
end

#subform?Boolean

Returns:

  • (Boolean)


19
20
21
# File 'lib/tree_struct/attribute.rb', line 19

def subform?
  !@nested_class.nil?
end

#validate_value!(value) ⇒ Object



23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
# File 'lib/tree_struct/attribute.rb', line 23

def validate_value!(value)
  if @nested_class
    if @array
      unless value.class == @parent.array_class
        raise ArgumentError.new(":#{@name} attribute value should be of class #{@parent.nested_class.name}::Array while attempt to assign value of class #{value.class.name}")
      end
      unless value.item_class == @nested_class
        raise ArgumentError.new(":#{@name} attribute value should be an array with items of class #{@nested_class.name} while attempt to assign an array with items of class #{value.item_class.name}")
      end

    else
      unless value.class == @nested_class
        raise ArgumentError.new(":#{@name} attribute value should be of class #{@nested_class.name} while attempt to assign value of class #{value.class.name}")
      end
    end
  end
end