Class: Parse::ParseFile

Inherits:
Object
  • Object
show all
Includes:
Util
Defined in:
lib/parse/file.rb

Instance Attribute Summary collapse

Instance Method Summary collapse

Methods included from Util

#string_keyed_hash

Constructor Details

#initialize(hash) ⇒ ParseFile

Returns a new instance of ParseFile.



8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
# File 'lib/parse/file.rb', line 8

def initialize hash
  hash = string_keyed_hash hash
  @name = hash['name']
  raise 'name is mandatory' unless @name
  @url = hash['url']
  @content = hash['content']
  @type = hash['type'] || {
    '.txt' => 'text/plain',
    '.html' => 'text/html',
    '.jpg' => 'image/jpeg',
    '.jpeg' => 'image/jpeg',
    '.png' => 'image/png',
    '.gif' => 'image/gif'
  }[File.extname(@name).downcase]
  @client = hash['parce_client'] || Parse::Client.default
end

Instance Attribute Details

#contentObject

Returns the value of attribute content.



6
7
8
# File 'lib/parse/file.rb', line 6

def content
  @content
end

#nameObject

Returns the value of attribute name.



6
7
8
# File 'lib/parse/file.rb', line 6

def name
  @name
end

#typeObject

Returns the value of attribute type.



6
7
8
# File 'lib/parse/file.rb', line 6

def type
  @type
end

#urlObject

Returns the value of attribute url.



6
7
8
# File 'lib/parse/file.rb', line 6

def url
  @url
end

Instance Method Details

#delete!Object



34
35
36
37
38
39
# File 'lib/parse/file.rb', line 34

def delete!
  raise "File should be fetched" unless @url
  @client.use_master_key do
    @client.call_api :delete, "files/#{@name}", nil, 'Content-Type' => nil, 'Accept' => nil
  end
end

#inspectObject



59
60
61
62
63
64
# File 'lib/parse/file.rb', line 59

def inspect
  content, @content = @content, '..snip..'
  ret = super
  @content = content
  ret
end

#load(&block) ⇒ Object



41
42
43
44
45
# File 'lib/parse/file.rb', line 41

def load &block
  open @url do |content| @content = content.read end unless @content
  block.call @content if block
  @content
end

#saveObject



25
26
27
28
29
30
31
32
# File 'lib/parse/file.rb', line 25

def save
  raise "Files cannot be updated." if @url
  @content = File.read @content if @type =~ %r|^image/|
  @client.call_api :post, "files/#{@name}", @content, 'Content-Type' => @type, 'Accept' => nil do |resp_body|
    @name = resp_body['name']
    @url = resp_body['url']
  end
end

#store(filepath = nil) ⇒ Object



47
48
49
50
51
52
53
54
55
56
57
# File 'lib/parse/file.rb', line 47

def store filepath=nil
  filepath ||= @name
  raise 'filepath is mandatory' unless filepath

  FileUtils.mkdir_p File.dirname(filepath)
  load do |content|
    open filepath, 'wb' do |file|
      file.write content
    end
  end
end

#to_hObject



66
67
68
69
70
71
# File 'lib/parse/file.rb', line 66

def to_h
  {
    "__type" => "File",
    "name" => @name
  }
end

#to_json(*args) ⇒ Object



73
74
75
# File 'lib/parse/file.rb', line 73

def to_json *args
  to_h.to_json
end