Sha256: 0f6a2e73b6b5d86acd4b84c5736665fe2a273e85c28e95e1511d2124dbc2472f

Contents?: true

Size: 1.77 KB

Versions: 1

Compression:

Stored size: 1.77 KB

Contents

require 'koine/attributes/hash_helper'

module Koine
  module Attributes
    class Builder
      attr_reader :attributes
      attr_reader :target

      def initialize(target:)
        @target = target
        @attributes = []
      end

      def build(name, driver)
        attributes.push(name.to_sym)
        build_getter(name, driver)
        build_setter(name, driver)
      end

      def build_getter(name, driver)
        target.class_eval do
          define_method(name) do
            instance_variable_get("@#{name}") || driver.default_value
          end
        end
      end

      def build_setter(name, driver)
        setter = "#{name}="

        target.class_eval do
          define_method(setter) do |*args|
            instance_variable_set("@#{name}", driver.coerce(*args))
          end
        end
      end

      def build_constructor(strict: true)
        valid_attributes = attributes

        target.class_eval do
          def initialize(args = {})
            initialize_attributes(args)
          end

          protected

          define_method(:initialize_attributes) do |constructor_args|
            invalid_attributes = []
            constructor_args = HashHelper.new.symbolize_keys(constructor_args)

            constructor_args.each do |name, _value|
              if valid_attributes.include?(name)
                setter = "#{name}=".to_sym
                send(setter, constructor_args[name])
                next
              end

              next unless strict
              invalid_attributes << name
            end

            unless invalid_attributes.empty?
              attributes = invalid_attributes.join(', ')
              raise ArgumentError, "Invalid attributes (#{attributes})"
            end
          end
        end
      end
    end
  end
end

Version data entries

1 entries across 1 versions & 1 rubygems

Version Path
koine-attributes-0.1.1 lib/koine/attributes/builder.rb