Sha256: 67ca845ddd5407a5ab7e7edb932c786fba8543cb7fe2fec82e25376759a6ff1f

Contents?: true

Size: 1.48 KB

Versions: 3

Compression:

Stored size: 1.48 KB

Contents

# frozen_string_literal: true

module Clamp
  module Attribute

    # Methods to generate attribute accessors.
    #
    module Declaration

      protected

      def define_accessors_for(attribute, &block)
        define_reader_for(attribute)
        define_default_for(attribute)
        if attribute.multivalued?
          define_appender_for(attribute, &block)
          define_multi_writer_for(attribute)
        else
          define_simple_writer_for(attribute, &block)
        end
      end

      private

      def define_reader_for(attribute)
        define_method(attribute.read_method) do
          attribute.of(self)._read
        end
      end

      def define_default_for(attribute)
        return false if attribute.default_value.nil?
        define_method(attribute.default_method) do
          attribute.default_value
        end
      end

      def define_simple_writer_for(attribute, &block)
        define_method(attribute.write_method) do |value|
          value = instance_exec(value, &block) if block
          attribute.of(self).set(value)
        end
      end

      def define_appender_for(attribute, &block)
        define_method(attribute.append_method) do |value|
          value = instance_exec(value, &block) if block
          attribute.of(self)._append(value)
        end
      end

      def define_multi_writer_for(attribute)
        define_method(attribute.write_method) do |values|
          attribute.of(self)._replace(values)
        end
      end

    end

  end
end

Version data entries

3 entries across 3 versions & 1 rubygems

Version Path
clamp-1.3.2 lib/clamp/attribute/declaration.rb
clamp-1.3.1 lib/clamp/attribute/declaration.rb
clamp-1.3.0 lib/clamp/attribute/declaration.rb