Class: Patm::Pattern::Struct::Builder

Inherits:
Object
  • Object
show all
Defined in:
lib/patm.rb

Instance Method Summary collapse

Constructor Details

#initialize(klass) ⇒ Builder

Returns a new instance of Builder.

Raises:

  • (ArgumentError)


393
394
395
396
# File 'lib/patm.rb', line 393

def initialize(klass)
  raise ArgumentError, "#{klass} is not Struct" unless klass.ancestors.include?(::Struct)
  @klass = klass
end

Instance Method Details

#call(*args) ⇒ Object

member_1_pat -> member_2_pat -> … -> Pattern => pattern -> Pattern



400
401
402
403
404
405
406
407
408
409
410
411
412
413
# File 'lib/patm.rb', line 400

def call(*args)
  if args.size == 1 && args.first.is_a?(::Hash)
    hash = args.first
    hash.keys.each do|k|
      raise ArgumentError, "#{k.inspect} is not member of #{@klass}" unless @klass.members.include?(k)
    end
    Struct.new(@klass, hash.each_with_object({}){|(k, plain), h|
      h[k] = Pattern.build_from(plain)
    })
  else
    raise ArgumentError, "Member size not match: expected #{@klass.members.size} but #{args.size}" unless args.size == @klass.members.size
    Struct.new(@klass, ::Hash[*@klass.members.zip(args.map{|a| Pattern.build_from(a) }).flatten(1)])
  end
end