class ArToAr::ActiveRecordToApplicationRecord

Public Class Methods

new(look_up_path=nil) click to toggle source
# File lib/ar_to_ar.rb, line 8
def initialize look_up_path=nil
  @current_path = look_up_path || Dir.pwd
  @all_file_names = Dir["#{@current_path}/app/models/**/*.rb"]
end

Public Instance Methods

start!() click to toggle source
# File lib/ar_to_ar.rb, line 13
def start!
  @all_file_names.each do |file_name|
    matched_line = new_line = nil
    matched_line = find_matched_line file_name
    next if matched_line.nil?
    model_name = find_model_name matched_line
    new_content = get_new_content model_name
    replace_content file_name, matched_line, new_content
  end

  copy_application_record_template
end

Private Instance Methods

copy_application_record_template() click to toggle source
# File lib/ar_to_ar.rb, line 55
def copy_application_record_template
  FileUtils.cp "#{File.expand_path(File.dirname(__FILE__))}/ar_to_ar/application_record_template.rb", "#{@current_path}/app/models/application_record.rb"
end
find_matched_line(file_path) click to toggle source

this method finds the line in app/models/*.rb which matches class ModelName < ActiveRecord::Base

# File lib/ar_to_ar.rb, line 30
def find_matched_line(file_path)
  File.open(file_path, "r++") do |file|
    return file.find { |line| line.force_encoding('UTF-8').match /(class(.+)<\s*ActiveRecord::Base)/ }
  end
end
find_model_name(line_of_interest) click to toggle source

line_of_interest is basically line of format class ModelName < ActiveRecord::Base this gets returned by find_matched_line method

# File lib/ar_to_ar.rb, line 39
def find_model_name line_of_interest
  model_name = line_of_interest.split('class ').last.split('<')[0]
  model_name = model_name.strip if model_name
  model_name
end
get_new_content(model_name) click to toggle source
# File lib/ar_to_ar.rb, line 45
def get_new_content model_name
  "class #{model_name} < ApplicationRecord\n"
end
replace_content(file_path, old_content, new_content) click to toggle source
# File lib/ar_to_ar.rb, line 49
def replace_content file_path, old_content, new_content
  file_text = File.read file_path
  sub_content = file_text.gsub old_content, new_content
  File.open(file_path, "w") {|file| file.puts sub_content}
end