Class: Parse::Relation

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

Instance Method Summary collapse

Constructor Details

#initialize(parent, column_name, hash) ⇒ Relation

Returns a new instance of Relation.



4
5
6
7
8
9
10
# File 'lib/parse/relation.rb', line 4

def initialize parent, column_name, hash
  @parent_object = parent
  @column_name = column_name
  @raw_hash = hash
  @added_pointers = []
  @removed_pointers = []
end

Instance Method Details

#add(item) ⇒ Object



12
13
14
15
16
17
18
# File 'lib/parse/relation.rb', line 12

def add item
  unless @removed_pointers.empty?
    raise ArgumentError.new('Please save for removed items before adding')
  end
  item = item.pointer if item.is_a?(Parse::Object)
  @added_pointers.push item
end

#changed?Boolean

Returns:

  • (Boolean)


53
54
55
# File 'lib/parse/relation.rb', line 53

def changed?
  (@added_pointers.size + @removed_pointers.size) != 0
end

#load(parse_client = Parse::Client.default) ⇒ Object



28
29
30
31
32
33
34
35
36
37
38
# File 'lib/parse/relation.rb', line 28

def load parse_client=Parse::Client.default
  unless @objects
    pointer = @parent_object.pointer
    key = @column_name
    related_class = Parse::Object @raw_hash['className']
    @objects = related_class.find :where => proc {
      related_to key, pointer
    }
  end
  @objects
end

#load!(parse_client = Parse::Client.default) ⇒ Object

TODO should be refactored



41
42
43
44
45
46
47
48
49
50
51
# File 'lib/parse/relation.rb', line 41

def load! parse_client=Parse::Client.default
  unless @objects
    pointer = @parent_object.pointer
    key = @column_name
    related_class = Parse::Object @raw_hash['className']
    @objects = related_class.find! :where => proc {
      related_to key, pointer
    }
  end
  @objects
end

#remove(item) ⇒ Object



20
21
22
23
24
25
26
# File 'lib/parse/relation.rb', line 20

def remove item
  unless @added_pointers.empty?
    raise ArgumentError.new('Please save for added items before removing')
  end
  item = item.pointer if item.is_a?(Parse::Object)
  @removed_pointers.push item
end

#to_hObject



57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
# File 'lib/parse/relation.rb', line 57

def to_h
  if not @added_pointers.empty?
    {
      "__op" => "AddRelation",
      "objects" => @added_pointers.map(&:to_h)
    }
  elsif not @removed_pointers.empty?
    {
      "__op" => "RemoveRelation",
      "objects" => @removed_pointers.map(&:to_h)
    }
  else
    {
      "__op" => "AddRelation",
      "objects" => [nil]
    }
  end
end

#to_json(*args) ⇒ Object



76
77
78
# File 'lib/parse/relation.rb', line 76

def to_json *args
  to_h.to_json
end