Class: AdGear::HasManyArray

Inherits:
Object
  • Object
show all
Includes:
Enumerable
Defined in:
lib/ad_gear/has_many_array.rb

Instance Method Summary collapse

Constructor Details

#initialize(name, klass, saved = nil) ⇒ HasManyArray

Returns a new instance of HasManyArray.



5
6
7
8
9
10
11
12
13
# File 'lib/ad_gear/has_many_array.rb', line 5

def initialize(name, klass, saved=nil)
  @name  = name.to_s.singularize.dasherize + "-attributes"
  @klass = klass
  @new   = []
  @saved = []
  saved.each do |obj|
    self << obj
  end if saved
end

Instance Method Details

#<<(object) ⇒ Object



15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
# File 'lib/ad_gear/has_many_array.rb', line 15

def <<(object)
  root = if object.kind_of?(Hash) then
           if object.has_key?("id") || object.has_key?(:id) then
             object = @klass.new(object)
             @saved
           else
             # Instantiate an object from the Hash, which will obviously be a new object
             object = @klass.new(object)
             @new
           end
         elsif object.respond_to?(:new_record?) && object.new_record?
           @new
         else
           @saved
         end
  root << object
end

#[](*args) ⇒ Object



48
49
50
# File 'lib/ad_gear/has_many_array.rb', line 48

def [](*args)
  combined[*args]
end

#each(&block) ⇒ Object



33
34
35
36
# File 'lib/ad_gear/has_many_array.rb', line 33

def each(&block)
  @saved.each(&block)
  @new.each(&block)
end

#empty?Boolean

Returns:

  • (Boolean)


44
45
46
# File 'lib/ad_gear/has_many_array.rb', line 44

def empty?
  combined.empty?
end

#firstObject



52
53
54
# File 'lib/ad_gear/has_many_array.rb', line 52

def first
  combined.first
end

#lastObject



56
57
58
# File 'lib/ad_gear/has_many_array.rb', line 56

def last
  combined.last
end

#lengthObject Also known as: size



38
39
40
# File 'lib/ad_gear/has_many_array.rb', line 38

def length
  @saved.length + @new.length
end

#to_xml(options = {}) ⇒ Object



60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
# File 'lib/ad_gear/has_many_array.rb', line 60

def to_xml(options={})
  xml = options[:builder] || Builder::XmlMarkup.new
  xml.__send__(@name) do
    unless @new.empty?
      xml.tag!(:new) do
        @new.each_with_index do |obj, index|
          obj.to_xml(options.merge(:root => "n" << index.to_s))
        end
      end
    end

    unless @saved.empty?
      @saved.each do |obj|
        obj.to_xml(options.merge(:root => "n" << obj.id.to_s))
      end
    end
  end
end