Class: Manioc::Struct

Inherits:
Object
  • Object
show all
Defined in:
lib/manioc/struct.rb

Defined Under Namespace

Classes: Config

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(**fields) ⇒ Struct

Returns a new instance of Struct.



52
53
54
55
56
57
# File 'lib/manioc/struct.rb', line 52

def initialize **fields
  fields = self.class.config.defaults.merge fields
  _validate fields
  _assign   fields
  freeze if Manioc.frozen? && self.class.config.immutable?
end

Class Method Details

.configure(fields: [], defaults: {}, mutable: Manioc.frozen?) ⇒ Object



32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
# File 'lib/manioc/struct.rb', line 32

def self.configure fields: [], defaults: {}, mutable: Manioc.frozen?
  config = Config.new.tap do |c|
    c.fields   = fields + defaults.keys
    c.defaults = defaults
    c.mutable  = mutable
  end

  Class.new Struct do
    define_singleton_method(:config) { config }

    config.fields.each do |field|
      if config.mutable
        attr_accessor field
      else
        attr_reader field
      end
    end
  end
end

Instance Method Details

#==(other) ⇒ Object



59
60
61
# File 'lib/manioc/struct.rb', line 59

def == other
  super || to_h == other.to_h
end

#inspectObject



71
72
73
74
75
# File 'lib/manioc/struct.rb', line 71

def inspect
  # :nocov:
  %|<#{self.class.name}(#{self.class.fields.join(', ')})>|
  # :nocov:
end

#to_hObject



67
68
69
# File 'lib/manioc/struct.rb', line 67

def to_h
  self.class.config.fields.each_with_object({}) { |field,h| h[field] = public_send field }
end

#with(**fields) ⇒ Object



63
64
65
# File 'lib/manioc/struct.rb', line 63

def with **fields
  self.class.new to_h.merge fields
end