Class: Bed::Caster

Inherits:
Object show all
Defined in:
lib/bed/caster.rb

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(buildable) ⇒ Caster

Returns a new instance of Caster.



7
8
9
# File 'lib/bed/caster.rb', line 7

def initialize(buildable)
  @buildable = buildable
end

Class Method Details

.cast(buildable) ⇒ Object



3
4
5
# File 'lib/bed/caster.rb', line 3

def self.cast(buildable)
  new(buildable).cast
end

Instance Method Details

#castObject

Raises:

  • (TypeError)


11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
# File 'lib/bed/caster.rb', line 11

def cast
  raise TypeError, "#{@buildable} does not respond to to_h" unless @buildable.respond_to?(:to_h)

  attributes = @buildable.to_h.transform_values do |value|
    case value
    in Hash
      self.class.cast(value)
    in Array
      value.map do |v|
        begin
          self.class.cast(v)
        rescue TypeError
          v
        end
      end
    else
      value
    end
  end

  cache_key = [attributes.keys]

  Thread.current[:__bed_cast_cache] ||= {}
  Thread.current[:__bed_cast_cache][cache_key] ||= (
    Data.define(*attributes.keys, &method(:definition))
  )
  Thread.current[:__bed_cast_cache][cache_key].new(**attributes)
end