Class: Code2rubylearning::FileHandling

Inherits:
Object
  • Object
show all
Defined in:
lib/code2rubylearning/filehandling.rb

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(file_name, options = { }) ⇒ FileHandling

Returns a new instance of FileHandling.



6
7
8
9
10
11
12
# File 'lib/code2rubylearning/filehandling.rb', line 6

def initialize(file_name, options = { })
  @name = nil
  @data = ""
  @type = ""
  load_data file_name
  identify_file_type if @name
end

Instance Attribute Details

#dataObject (readonly)

Returns the value of attribute data.



4
5
6
# File 'lib/code2rubylearning/filehandling.rb', line 4

def data
  @data
end

#nameObject (readonly)

Returns the value of attribute name.



4
5
6
# File 'lib/code2rubylearning/filehandling.rb', line 4

def name
  @name
end

#typeObject (readonly)

Returns the value of attribute type.



4
5
6
# File 'lib/code2rubylearning/filehandling.rb', line 4

def type
  @type
end

Instance Method Details

#identify_file_typeObject

Sets the @type for this file check extension for known types if extension fails try checking the first line it may contain #! and give a clue.



28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
# File 'lib/code2rubylearning/filehandling.rb', line 28

def identify_file_type
  @type = "text"
  
  data_lines = @data.split("\n")

  # check for a ruby file
  if @name.include?(".rb") ||  data_lines.first.include?("#!") && data_lines.first.include?("ruby")
    @type = "ruby"
  end

  # check for a python file
  if @name.include?(".py") ||  data_lines.first.include?("#!") && data_lines.first.include?("python")
    @type = "python"
  end

end

#load_data(file_name) ⇒ Object



14
15
16
17
18
19
20
21
22
# File 'lib/code2rubylearning/filehandling.rb', line 14

def load_data file_name

  if file_name
    if File.exists?(file_name)
      @name = file_name
      @data = IO.read(@name)
    end
  end
end