Module: Mexico::Util::FancyContainer

Included in:
FileSystem::FiestaDocument
Defined in:
lib/mexico/util/fancy_container.rb

Overview

This module contains various helper methods.

Instance Method Summary collapse

Instance Method Details

#add_fancy_container(container_name, p_back_collection_name = nil) ⇒ Object

module ClassMethods


25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
# File 'lib/mexico/util/fancy_container.rb', line 25

def add_fancy_container(container_name, p_back_collection_name=nil)
  back_collection_name = p_back_collection_name.nil? ? "#{container_name.to_s}_container" : p_back_collection_name
  define_method(container_name) do |*args|
    coll = Array.new(instance_variable_get("@#{back_collection_name}"))
    if args.is_a?(Enumerable)
      if args.length==1
        if args.first.is_a?(String)
          # one argument in string form: assume an identifier, return a single object or nil
          return instance_variable_get("@#{back_collection_name}").find{|x| x.identifier == args.first }
        end
        if args.first.is_a?(Hash)
          # one argument in string form: assume a hash with conditions
          args.first.each do |key,val|
            if val.is_a?(String)
              coll.select!{|c| c.send(key).to_s==val }
            elsif val.is_a?(Regexp)
              coll.select!{|c| c.send(key).to_s=~val }
            end
          end
          return coll
        end
        if args.first.is_a?(Integer)
          return coll[args.first]
        end
      end
    end
    # otherwise:
    orig_coll = instance_variable_get("@#{back_collection_name}")
    orig_coll = [] if orig_coll.nil?
    Array.new(orig_coll)
  end
end