Class: Soryo::FileInstance

Inherits:
Object
  • Object
show all
Defined in:
lib/classes/fileinstance.rb

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(file_path) ⇒ FileInstance

Returns a new instance of FileInstance.



10
11
12
# File 'lib/classes/fileinstance.rb', line 10

def initialize(file_path)
    @file_path = Pathname.new(file_path)
end

Instance Attribute Details

#file_pathObject (readonly)

Returns the value of attribute file_path.



8
9
10
# File 'lib/classes/fileinstance.rb', line 8

def file_path
  @file_path
end

Instance Method Details

#_symbolize(obj) ⇒ Object



49
50
51
52
53
# File 'lib/classes/fileinstance.rb', line 49

def _symbolize(obj)
    return obj.inject({}){|memo,(k,v)| memo[k.to_sym] =  _symbolize(v); memo} if obj.is_a? Hash
    return obj.inject([]){|memo,v    | memo           << _symbolize(v); memo} if obj.is_a? Array
    return obj
end

#existance?Boolean

Returns:

  • (Boolean)


25
26
27
# File 'lib/classes/fileinstance.rb', line 25

def existance?
    File.exists?(file_path)
end

#shortnameObject



55
56
57
# File 'lib/classes/fileinstance.rb', line 55

def shortname
    File.basename(@file_path, '.*')
end

#to_hashObject



35
36
37
38
39
40
41
42
43
44
45
46
47
# File 'lib/classes/fileinstance.rb', line 35

def to_hash
    if self.existance?
        if File.extname(@file_path) == '.json'
            json_hash = JSON.parse(self.to_s)
        elsif ['.yaml', '.yml'].include? File.extname(@file_path)
            yaml_hash = YAML.load(self.to_s)
        else
            raise 'Must be a JSON or YAML file'
        end
     else
         raise 'NoFileFound'
     end
end

#to_sObject



14
15
16
17
18
19
20
21
22
23
# File 'lib/classes/fileinstance.rb', line 14

def to_s
    if self.existance?
        file = File.open(@file_path, 'r')
        file_text = file.read
        file.close
        file_text
    else
        raise 'NoFileFound'
    end
end

#write(file_contents) ⇒ Object



29
30
31
32
33
# File 'lib/classes/fileinstance.rb', line 29

def write(file_contents)
    file = File.open(@file_path, 'w')
    file.write(file_contents)
    file.close
end