module Dry::Struct::Setters
Constants
- VERSION
Public Class Methods
define_setter_for(struct:, attribute:, type:)
click to toggle source
# File lib/dry/struct/setters.rb, line 37 def self.define_setter_for(struct:, attribute:, type:) attribute = remove_trailing_question_mark(attribute) setter = "#{attribute}=".to_sym struct.class_eval do unless instance_methods.include?(setter) define_method(setter) do |value| @attributes[attribute] = type.call(value) end setter end end end
included(struct)
click to toggle source
# File lib/dry/struct/setters.rb, line 11 def self.included(struct) struct.extend(ClassMethods) struct.schema.each do |key| Dry::Struct::Setters.define_setter_for(struct: struct, attribute: key.name, type: key.type) end def []=(key, value) if self.class.schema.key?(key) public_send("#{key}=", value) else raise Dry::Struct::MissingAttributeError, key end end end
remove_trailing_question_mark(attribute)
click to toggle source
# File lib/dry/struct/setters.rb, line 52 def self.remove_trailing_question_mark(attribute) # See https://github.com/tbuehlmann/dry-struct-setters/issues/2 attribute.to_s.chomp('?').to_sym end
Public Instance Methods
[]=(key, value)
click to toggle source
# File lib/dry/struct/setters.rb, line 18 def []=(key, value) if self.class.schema.key?(key) public_send("#{key}=", value) else raise Dry::Struct::MissingAttributeError, key end end