Class: ActiveFactory::LinkingContext

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

Overview

provides methods that refer models in models {} block

Instance Method Summary collapse

Constructor Details

#initialize(model_names, containers_hash, context) ⇒ LinkingContext

Returns a new instance of LinkingContext.



362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
# File 'lib/active_factory.rb', line 362

def initialize model_names, containers_hash, context
  @context = context
  h = containers_hash

  obj_class_eval do
    model_names.each { |name|

      define_method name do |*args|
        not args.many? or raise "0 or 1 arguments expected, got: #{args.inspect}"

        if args.none?
          h[name].singleton
        else
          h[name].singleton.zip_merge(args[0])

        end.build.make_linker
      end

      define_method :"#{name.to_s.pluralize}" do |*args|

        if args.none?
          h[name]

        elsif args[0].is_a? Fixnum and args.one?
          h[name].create(args[0])

        elsif args.all? { |arg| arg.is_a? Hash }
          h[name].create(args.size).zip_merge(*args)

        else
          raise "expected no args, or single integer, or several hashes, got: #{args.inspect}"

        end.build.make_linker
      end

      define_method :"#{name}_" do
        h[name].singleton.make_linker
      end

      define_method :"#{name.to_s.pluralize}_" do |count|
        h[name].create(count).make_linker
      end
    }
  end
end

Dynamic Method Handling

This class handles dynamic methods through the method_missing method

#method_missing(*args, &block) ⇒ Object (private)



416
417
418
419
420
421
422
# File 'lib/active_factory.rb', line 416

def method_missing *args, &block
  if block
    @context.send *args, &block
  else
    @context.send *args
  end
end