Skip to content

Commit 0d87191

Browse files
committed
Memoize schema
1 parent 7e723da commit 0d87191

File tree

2 files changed

+7
-17
lines changed

2 files changed

+7
-17
lines changed

lib/dry/struct.rb

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,4 @@
1+
require 'dry/core/constants'
12
require 'dry-types'
23

34
require 'dry/struct/version'
@@ -56,6 +57,7 @@ module Dry
5657
# refactoring.title #=> 'Refactoring'
5758
# refactoring.subtitle #=> 'Improving the Design of Existing Code'
5859
class Struct
60+
include Dry::Core::Constants
5961
extend ClassInterface
6062

6163
# {Dry::Types::Hash} subclass with specific behaviour defined for
@@ -64,6 +66,10 @@ class Struct
6466
defines :input
6567
input Types['coercible.hash']
6668

69+
# @return [Hash{Symbol => Dry::Types::Definition, Dry::Struct}]
70+
defines :schema
71+
schema EMPTY_HASH
72+
6773
# Sets or retrieves {#constructor} type as a symbol
6874
#
6975
# @note All examples below assume that you have defined {Struct} with

lib/dry/struct/class_interface.rb

Lines changed: 1 addition & 17 deletions
Original file line numberDiff line numberDiff line change
@@ -12,20 +12,12 @@ module ClassInterface
1212

1313
include Dry::Types::Builder
1414

15-
# @param [Module] base
16-
def self.extended(base)
17-
base.instance_variable_set(:@schema, EMPTY_HASH)
18-
end
19-
2015
# @param [Class] klass
2116
def inherited(klass)
2217
super
2318

24-
klass.instance_variable_set(:@schema, EMPTY_HASH)
2519
klass.equalizer Equalizer.new(*schema.keys)
2620
klass.send(:include, klass.equalizer)
27-
28-
klass.attributes(EMPTY_HASH) unless equal?(Struct)
2921
end
3022

3123
# Adds an attribute for this {Struct} with given `name` and `type`
@@ -70,9 +62,7 @@ def attribute(name, type)
7062
def attributes(new_schema)
7163
check_schema_duplication(new_schema)
7264

73-
prev_schema = schema
74-
75-
@schema = prev_schema.merge(new_schema)
65+
schema schema.merge(new_schema)
7666
input Types['coercible.hash'].public_send(constructor_type, schema)
7767

7868
attr_reader(*new_schema.keys)
@@ -91,12 +81,6 @@ def check_schema_duplication(new_schema)
9181
end
9282
private :check_schema_duplication
9383

94-
# @return [Hash{Symbol => Dry::Types::Definition, Dry::Struct}]
95-
def schema
96-
super_schema = superclass.respond_to?(:schema) ? superclass.schema : EMPTY_HASH
97-
super_schema.merge(@schema)
98-
end
99-
10084
# @param [Hash{Symbol => Object},Dry::Struct] attributes
10185
# @raise [Struct::Error] if the given attributes don't conform {#schema}
10286
# with given {#constructor_type}

0 commit comments

Comments
 (0)