Module: Dry::Struct::Setters

Included in:
WithSetters
Defined in:
lib/dry/struct/setters.rb,
lib/dry/struct/setters/version.rb,
lib/dry/struct/setters/mass_assignment.rb

Defined Under Namespace

Modules: ClassMethods, MassAssignment

Constant Summary collapse

VERSION =
'0.1.0'

Class Method Summary collapse

Class Method Details

.define_setter_for(struct:, attribute:, type:) ⇒ Object



29
30
31
32
33
34
35
36
37
38
39
40
41
# File 'lib/dry/struct/setters.rb', line 29

def self.define_setter_for(struct:, attribute:, type:)
  setter = "#{attribute}=".to_sym

  struct.class_eval do
    unless instance_methods.include?(setter)
      define_method(setter) do |value|
        instance_variable_set("@#{attribute}", type.call(value))
      end

      setter
    end
  end
end

.included(struct) ⇒ Object



11
12
13
14
15
16
17
# File 'lib/dry/struct/setters.rb', line 11

def self.included(struct)
  struct.extend(ClassMethods)

  struct.schema.each do |attribute, type|
    Dry::Struct::Setters.define_setter_for(struct: struct, attribute: attribute, type: type)
  end
end