Module: Low::TypeAccessors
- Defined in:
- lib/definitions/type_accessors.rb
Overview
Usage:
type_accessor name: String # => @name getter and @name=() setter type_accessor name: String | 'Cher'
type_reader name: String type_reader name: String | 'Cher' # defaults to 'Cher' if nil
type_writer name: String type_writer name: String | nil # accepts String or nil
Instance Method Summary collapse
- #type_accessor(named_expressions) ⇒ Object
- #type_reader(named_expressions) ⇒ Object
- #type_writer(named_expressions) ⇒ Object
Instance Method Details
#type_accessor(named_expressions) ⇒ Object
59 60 61 62 63 64 |
# File 'lib/definitions/type_accessors.rb', line 59 def type_accessor(named_expressions) named_expressions.each do |name, expression| type_reader({ name => expression }) type_writer({ name => expression }) end end |
#type_reader(named_expressions) ⇒ Object
20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 |
# File 'lib/definitions/type_accessors.rb', line 20 def type_reader(named_expressions) named_expressions.each do |name, exp| last_caller = caller_locations(1, 1).first file_path = last_caller.path scope = "#{self}##{name}" expression = cast_type_expression(exp) # Source usually defined on file load with access to lines in a source file, but type accessors are defined on class load. source = ::Lowkey::Source.new(file_path:, scope:, lines: [], start_line: last_caller.lineno, end_line: last_caller.lineno) proxy = ::Lowkey::ReturnProxy.new(name:, source:, expression:) define_method(name) do value = instance_variable_get("@#{name}") expression.validate!(value:, proxy:) value end end end |
#type_writer(named_expressions) ⇒ Object
40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 |
# File 'lib/definitions/type_accessors.rb', line 40 def type_writer(named_expressions) named_expressions.each do |name, expression| last_caller = caller_locations(1, 1).first file_path = last_caller.path scope = "#{self}##{name}" expression = cast_type_expression(expression) # Source usually defined on file load with access to lines in a source file, but type accessors are defined on class load. source = ::Lowkey::Source.new(file_path:, scope:, lines: [], start_line: last_caller.lineno, end_line: last_caller.lineno) proxy = ::Lowkey::ParamProxy.new(name:, source:, type: :pos_req, position: nil, expression:) define_method("#{name}=") do |value| expression.validate!(value:, proxy:) instance_variable_set("@#{name}", value) end end end |