Class: Structure::Builder

Inherits:
Object
  • Object
show all
Defined in:
lib/structure/builder.rb

Overview

Builder class for accumulating attribute definitions

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initializeBuilder

Returns a new instance of Builder.



10
11
12
13
14
# File 'lib/structure/builder.rb', line 10

def initialize
  @mappings = {}
  @types = {}
  @defaults = {}
end

Instance Attribute Details

#defaultsObject (readonly)

Returns the value of attribute defaults.



8
9
10
# File 'lib/structure/builder.rb', line 8

def defaults
  @defaults
end

#mappingsObject (readonly)

Returns the value of attribute mappings.



8
9
10
# File 'lib/structure/builder.rb', line 8

def mappings
  @mappings
end

#typesObject (readonly)

Returns the value of attribute types.



8
9
10
# File 'lib/structure/builder.rb', line 8

def types
  @types
end

Instance Method Details

#attribute(name, type = nil, from: nil, default: nil, &block) ⇒ Object



16
17
18
19
20
21
22
23
24
25
26
27
28
# File 'lib/structure/builder.rb', line 16

def attribute(name, type = nil, from: nil, default: nil, &block)
  # Always store in mappings - use attribute name as default source
  @mappings[name] = from || name.to_s
  @defaults[name] = default unless default.nil?

  if type && block
    raise ArgumentError, "Cannot specify both type and block for :#{name}"
  elsif block
    @types[name] = block
  elsif type
    @types[name] = Types.coerce(type)
  end
end

#attributesObject

Deduced from mappings - maintains order of definition



31
32
33
# File 'lib/structure/builder.rb', line 31

def attributes
  @mappings.keys
end

#predicate_methodsObject

Deduced from types that are boolean



36
37
38
39
40
41
42
43
# File 'lib/structure/builder.rb', line 36

def predicate_methods
  @types.filter_map do |name, type_lambda|
    if type_lambda == Types.boolean
      predicate_name = "#{name}?"
      [predicate_name.to_sym, name]
    end
  end.to_h
end