-
-
Notifications
You must be signed in to change notification settings - Fork 62
/
struct.rb
228 lines (209 loc) · 6.76 KB
/
struct.rb
1
2
3
4
5
6
7
8
9
10
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
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
# frozen_string_literal: true
require "weakref"
require "dry/core"
require "dry/types"
require "dry/struct/class_interface"
require "dry/struct/errors"
require "dry/struct/version"
module Dry
# Constructor method for easily creating a {Dry::Struct}.
# @return [Dry::Struct]
# @example
# require 'dry-struct'
#
# module Types
# include Dry.Types()
# end
#
# Person = Dry.Struct(name: Types::String, age: Types::Integer)
# matz = Person.new(name: "Matz", age: 52)
# matz.name #=> "Matz"
# matz.age #=> 52
#
# Test = Dry.Struct(expected: Types::String) { schema(schema.strict) }
# Test[expected: "foo", unexpected: "bar"]
# #=> Dry::Struct::Error: [Test.new] unexpected keys [:unexpected] in Hash input
def self.Struct(attributes = Dry::Core::Constants::EMPTY_HASH, &block)
Class.new(Dry::Struct) do
attributes.each { |a, type| attribute a, type }
module_eval(&block) if block
end
end
# Typed {Struct} with virtus-like DSL for defining schema.
#
# ### Differences between dry-struct and virtus
#
# {Struct} look somewhat similar to [Virtus][] but there are few significant differences:
#
# * {Struct}s don't provide attribute writers and are meant to be used
# as "data objects" exclusively.
# * Handling of attribute values is provided by standalone type objects from
# [`dry-types`][].
# * Handling of attribute hashes is provided by standalone hash schemas from
# [`dry-types`][].
# * Struct classes quack like [`dry-types`][], which means you can use them
# in hash schemas, as array members or sum them
#
# {Struct} class can specify a constructor type, which uses [hash schemas][]
# to handle attributes in `.new` method.
#
# [`dry-types`]: https://github.com/dry-rb/dry-types
# [Virtus]: https://github.com/solnic/virtus
# [hash schemas]: http://dry-rb.org/gems/dry-types/hash-schemas
#
# @example
# require 'dry-struct'
#
# module Types
# include Dry.Types()
# end
#
# class Book < Dry::Struct
# attribute :title, Types::String
# attribute :subtitle, Types::String.optional
# end
#
# rom_n_roda = Book.new(
# title: 'Web Development with ROM and Roda',
# subtitle: nil
# )
# rom_n_roda.title #=> 'Web Development with ROM and Roda'
# rom_n_roda.subtitle #=> nil
#
# refactoring = Book.new(
# title: 'Refactoring',
# subtitle: 'Improving the Design of Existing Code'
# )
# refactoring.title #=> 'Refactoring'
# refactoring.subtitle #=> 'Improving the Design of Existing Code'
class Struct
extend Core::Extensions
include Core::Constants
extend ClassInterface
extend Core::Deprecations[:"dry-struct"]
class << self
# override `Dry::Types::Builder#prepend`
define_method(:prepend, ::Module.method(:prepend))
def loader
@loader ||= ::Zeitwerk::Loader.new.tap do |loader|
root = ::File.expand_path("..", __dir__)
loader.tag = "dry-struct"
loader.inflector = ::Zeitwerk::GemInflector.new("#{root}/dry-struct.rb")
loader.push_dir(root)
loader.ignore(
"#{root}/dry-struct.rb",
"#{root}/dry/struct/{class_interface,errors,extensions,printer,value,version}.rb",
"#{root}/dry/struct/extensions"
)
end
end
end
loader.setup
include ::Dry::Equalizer(:__attributes__, inspect: false, immutable: true)
# {Dry::Types::Hash::Schema} subclass with specific behaviour defined for
# @return [Dry::Types::Hash::Schema]
defines :schema
schema Types["coercible.hash"].schema(EMPTY_HASH)
defines :abstract_class
abstract
# @!attribute [Hash{Symbol => Object}] attributes
attr_reader :attributes
alias_method :__attributes__, :attributes
# @param [Hash, #each] attributes
def initialize(attributes)
@attributes = attributes
end
# Retrieves value of previously defined attribute by its' `name`
#
# @param [String] name
# @return [Object]
#
# @example
# class Book < Dry::Struct
# attribute :title, Types::String
# attribute :subtitle, Types::String.optional
# end
#
# rom_n_roda = Book.new(
# title: 'Web Development with ROM and Roda',
# subtitle: nil
# )
# rom_n_roda[:title] #=> 'Web Development with ROM and Roda'
# rom_n_roda[:subtitle] #=> nil
def [](name)
@attributes.fetch(name) do
raise MissingAttributeError.new(attribute: name, klass: self.class)
end
end
# Converts the {Dry::Struct} to a hash with keys representing
# each attribute (as symbols) and their corresponding values
#
# @return [Hash{Symbol => Object}]
#
# @example
# class Book < Dry::Struct
# attribute :title, Types::String
# attribute :subtitle, Types::String.optional
# end
#
# rom_n_roda = Book.new(
# title: 'Web Development with ROM and Roda',
# subtitle: nil
# )
# rom_n_roda.to_hash
# #=> {title: 'Web Development with ROM and Roda', subtitle: nil}
def to_h
self.class.schema.each_with_object({}) do |key, result|
result[key.name] = Hashify[self[key.name]] if attributes.key?(key.name)
end
end
# TODO: remove in 2.0
alias_method :to_hash, :to_h
# Create a copy of {Dry::Struct} with overriden attributes
#
# @param [Hash{Symbol => Object}] changeset
#
# @return [Struct]
#
# @example
# class Book < Dry::Struct
# attribute :title, Types::String
# attribute :subtitle, Types::String.optional
# end
#
# rom_n_roda = Book.new(
# title: 'Web Development with ROM and Roda',
# subtitle: '2nd edition'
# )
# #=> #<Book title="Web Development with ROM and Roda" subtitle="2nd edition">
#
# rom_n_roda.new(subtitle: '3rd edition')
# #=> #<Book title="Web Development with ROM and Roda" subtitle="3rd edition">
def new(changeset)
new_attributes = self.class.schema.apply(
changeset,
skip_missing: true,
resolve_defaults: false
)
self.class.load(__attributes__.merge(new_attributes))
rescue Types::SchemaError, Types::MissingKeyError, Types::UnknownKeysError => e
raise Error, "[#{self}.new] #{e}"
end
alias_method :__new__, :new
# @return [String]
def inspect
klass = self.class
attrs = klass.attribute_names.map { |key| " #{key}=#{@attributes[key].inspect}" }.join
"#<#{klass.name || klass.inspect}#{attrs}>"
end
# Pattern matching support
#
# @api private
def deconstruct_keys(_keys)
attributes
end
end
end
require "dry/struct/extensions"
require "dry/struct/printer"
require "dry/struct/value"