Sha256: 1ca173ef992904c5119c6097e1adf08dcf312571a4fc26df3f0ec1c1ee03d31d

Contents?: true

Size: 1.12 KB

Versions: 6

Compression:

Stored size: 1.12 KB

Contents

module JustBackgammon

  # = Common
  #
  # Mixin that allows the class to have a custom load method
  # It allows initializing by arrays, hashes or objects with the same class.
  module Common

    # Method that initializing an object by arrays, hashes or objects with the same class.
    # Returns the object or array of objects.
    # Will raise error if elements of array are not all the same Class.
    # Will raise error if argument is not Hash, Array or the same Class.
    #
    # @param [Array<Hash>, Hash, Object] argument
    #   The initialization data.
    #
    # @return [Array<Object>, Object]
    def load(argument)
      case argument
      when Hash
        self.new(argument)
      when Array
        case
        when argument.all? { |o| o.instance_of?(Hash) }
          argument.map { |o| self.new(o) }
        when argument.all? { |o| o.instance_of?(self) }
          argument
        else
          raise ArgumentError, "elements of array must have the same class"
        end
      when self
        argument
      else
        raise ArgumentError, "argument needs to be a Hash, Array or #{self}"
      end
    end
  end
end

Version data entries

6 entries across 6 versions & 1 rubygems

Version Path
just_backgammon-1.0.1 lib/just_backgammon/common.rb
just_backgammon-1.0.0 lib/just_backgammon/common.rb
just_backgammon-0.2.0 lib/just_backgammon/common.rb
just_backgammon-0.1.2 lib/just_backgammon/common.rb
just_backgammon-0.1.1 lib/just_backgammon/common.rb
just_backgammon-0.1.0 lib/just_backgammon/common.rb