Class: ProjectFile

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

Class Method Summary collapse

Class Method Details

.add_line(name, end_model, line_content) ⇒ Object



46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
# File 'lib/project_file.rb', line 46

def self.add_line(name, end_model, line_content)
  open_close(name, 'model') do |file, tempfile|
    line_found = false
    file.each do |line|
      if (line.include?('end') || line.include?("through: :#{end_model}")) && !line_found
        line_found = true
        line_association = ''
        line_content.each do |key, value|
          line_association << if %w[has_many has_one].include?(key)
                                "  #{key} #{value}"
                              else
                                ", #{key}: #{value}"
                              end
        end

        line_association << "\n"
        tempfile << line_association
      end
      tempfile << line
    end
  end
end

.open_close(name, type, &block) ⇒ Object



2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
# File 'lib/project_file.rb', line 2

def self.open_close(name, type, &block)
  case type
  when 'migration'
    tempfile_name = './db/migrate/migration_update.rb'
    file_name = Dir.glob("./db/migrate/*_#{name.pluralize}.rb").first
  when 'model'
    tempfile_name = './app/models/model_update.rb'
    file_name = "./app/models/#{name}.rb"
  end

  tempfile = File.open(tempfile_name, 'w')
  file = File.new(file_name)

  block.call(file, tempfile)

  file.close
  tempfile.close

  FileUtils.mv(
    tempfile_name,
    file_name
  )
end

.update_line(name, type, keywords, line_content) ⇒ Object



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

def self.update_line(name, type, keywords, line_content)
  open_close(name, type) do |file, tempfile|
    file.each do |line|
      if line.match(keywords)
        line.gsub!("\n", ' ')
        line_content.each do |key, value|
          if line.include? key
            line.gsub!(/#{key}: .*([, ])/, "#{key}: #{value}#{Regexp.last_match(1)}")
          else
            line << ", #{key}: #{value}"
          end
        end
        line << "\n"

      end
      tempfile << line
    end
  end
end