Sha256: 42d43945f4afa7a801247c6f4e6a13393b2ded1c5a35802be70fe3772881ec5f

Contents?: true

Size: 1010 Bytes

Versions: 4

Compression:

Stored size: 1010 Bytes

Contents

module Aldous
  class SimpleDto
    attr_reader :_data

    def initialize(data = {})
      @_data = data

      handle_errors_and_messages
      define_accessors
    end

    def errors
      @errors ||= []
    end

    def messages
      @messages ||= []
    end

    private

    def handle_errors_and_messages
      # ensure that any errors or messages end up in the appropriate array
      _data.each_pair do |key, value|
        if key.to_s == 'errors'
          @errors = [value].flatten.compact
        elsif key.to_s == 'messages'
          @messages = [value].flatten.compact
        end
      end
    end

    def define_accessors
      self.class.class_exec(_data) do |_data|
        _data.each_key do |key|
          next if key.to_s == 'errors' || key.to_s == 'messages'
          # do nothing if method is already defined
          next if instance_methods(false).include?(key.to_sym)

          define_method key do
            @_data[key]
          end
        end
      end
    end
  end
end

Version data entries

4 entries across 4 versions & 1 rubygems

Version Path
aldous-1.1.3 lib/aldous/simple_dto.rb
aldous-1.1.2 lib/aldous/simple_dto.rb
aldous-1.0.1 lib/aldous/simple_dto.rb
aldous-1.0.0 lib/aldous/simple_dto.rb