Class: TypedStruct
- Inherits:
-
Struct
- Object
- Struct
- TypedStruct
- Includes:
- TypeChecking
- Defined in:
- lib/typed_struct.rb,
lib/typed_struct/version.rb,
lib/typed_struct/type_checking.rb
Defined Under Namespace
Modules: TypeChecking
Constant Summary collapse
- OVERRIDING_NATIVE_METHOD_MSG =
"*** WARNING *** property %s overrides a native method in #{name}. Consider using something else (called from %s)".freeze
- Options =
TypedStruct.new({ default: nil }, default: Rbs("untyped"))
- VERSION =
"0.1.4"
Class Method Summary collapse
Instance Method Summary collapse
-
#initialize(**attrs) ⇒ TypedStruct
constructor
A new instance of TypedStruct.
Constructor Details
#initialize(**attrs) ⇒ TypedStruct
Returns a new instance of TypedStruct.
56 57 58 59 60 61 62 63 64 65 66 67 |
# File 'lib/typed_struct.rb', line 56 def initialize(**attrs) opts = self.__class__. vals = opts[:types].to_h do |prop, expected_type| value = attrs.fetch(prop, opts[:options][:default]) unless val_is_type? value, expected_type raise "Unexpected type #{value.class} for #{prop.inspect} (expected #{expected_type})" end [prop, value] end super **vals end |
Class Method Details
.new(opts = Options.new, **properties) ⇒ Object
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 |
# File 'lib/typed_struct.rb', line 21 def new(opts = Options.new, **properties) properties.each_key do |prop| if method_defined?(prop) $stdout.puts OVERRIDING_NATIVE_METHOD_MSG % [prop.inspect, caller(3).first] end end super(*properties.keys, keyword_init: true).tap do |klass| klass.class.instance_eval do include TypeChecking attr_reader :options end klass.instance_eval do @options = { types: properties, options: opts } define_method :[]= do |key, val| prop = properties[key] unless val_is_type? val, prop raise "Unexpected type #{val.class} for #{key.inspect} (expected #{prop})" end super key, val end properties.each_key do |k| define_method :"#{k}=" do |val| self[k] = val end end end end end |