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.4.0'

Class Method Summary collapse

Instance Method Summary collapse

Class Method Details

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



37
38
39
40
41
42
43
44
45
46
47
48
49
50
# 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) ⇒ Object



11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
# 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) ⇒ Object



52
53
54
55
# 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

Instance Method Details

#[]=(key, value) ⇒ Object



18
19
20
21
22
23
24
# 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