Class: ShareProgress::VariantCollection

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

Instance Method Summary collapse

Constructor Details

#initialize(variants_hash = nil) ⇒ VariantCollection

Returns a new instance of VariantCollection.



7
8
9
10
# File 'lib/share_progress/variant_collection.rb', line 7

def initialize(variants_hash=nil)
  @variants = []
  update_variants(variants_hash) unless variants_hash.nil?
end

Instance Method Details

#add_or_update(variant) ⇒ Object



33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
# File 'lib/share_progress/variant_collection.rb', line 33

def add_or_update(variant)
  variant_obj = find(variant)
  if variant_obj.nil?
    if variant.is_a? Variant
      @variants.push variant
      variant_obj = variant
    else
      variant_obj = create_variant(variant)
      @variants.push(variant_obj)
    end
  else
    variant_obj.update_attributes(variant)
  end
  variant_obj
end

#find(mystery_variant) ⇒ Object



61
62
63
64
65
66
67
68
69
# File 'lib/share_progress/variant_collection.rb', line 61

def find(mystery_variant)
  if mystery_variant.is_a? Variant
    find_variant_by_obj(mystery_variant)
  elsif mystery_variant.is_a? Hash
    find_variant_by_id(Utils.symbolize_keys(mystery_variant)[:id])
  elsif mystery_variant.is_a? Fixnum
    find_variant_by_id(mystery_variant)
  end
end

#remove(variant) ⇒ Object



49
50
51
52
53
54
55
# File 'lib/share_progress/variant_collection.rb', line 49

def remove(variant)
  target = find(variant)
  destroyed = target.destroy
  return false if destroyed == false
  @variants.select!{ |v| v.id != target.id }
  destroyed
end

#serializeObject



23
24
25
26
27
28
29
30
31
# File 'lib/share_progress/variant_collection.rb', line 23

def serialize
  serialized = {}
  @variants.each do |variant_obj|
    type_name = variant_obj.type.to_sym
    serialized[type_name] ||= []
    serialized[type_name].push variant_obj.serialize
  end
  serialized
end

#update_variants(variants_hash) ⇒ Object



12
13
14
15
16
17
18
19
20
21
# File 'lib/share_progress/variant_collection.rb', line 12

def update_variants(variants_hash)
  survivors = []
  variants_hash.each_pair do |variant_type, variants_list|
    variants_list.each do |variant_hash|
      added = add_or_update(variant_hash)
      survivors.push(added)
    end
  end
  @variants.select!{ |v| survivors.include? v }
end

#variantsObject



57
58
59
# File 'lib/share_progress/variant_collection.rb', line 57

def variants
  @variants
end