Class: Manioc::Struct
- Inherits:
-
Object
- Object
- Manioc::Struct
- Defined in:
- lib/manioc/struct.rb
Defined Under Namespace
Classes: Config
Class Method Summary collapse
Instance Method Summary collapse
- #==(other) ⇒ Object
-
#initialize(**fields) ⇒ Struct
constructor
A new instance of Struct.
- #inspect ⇒ Object
- #to_h ⇒ Object
- #with(**fields) ⇒ Object
Constructor Details
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 |
#inspect ⇒ Object
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_h ⇒ Object
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 |