实际上,我正在使用此方法来替换文件的给定内容:
def self.fix_authorgroup_work(title, name, email_business, company_name, company_division)
agroup = "#{title}/de-DE/Author_Group.xml"
namechomp = name.chomp
# @note Split the variable to the array title[*]
name = namechomp.split(' ')
firstname = name[0]
surname = name[1]
# @note Author Group: Change the default stuff to the present user
puts 'Replace the default content with the new content from the user (Authors_Group)'.color(:yellow)
text = File.read(agroup)
vorname = text.gsub('Enter your first name here.', "#{firstname}")
puts vorname
File.open(agroup, 'w') { |file|
file.puts vorname
}
text = File.read(agroup)
nachname = text.gsub('Enter your surname here.', "#{surname}")
puts nachname
File.open(agroup, 'w') { |file|
file.puts nachname
}
text = File.read(agroup)
email = text.gsub('Enter your email address here.', "#{email_business}")
puts email
File.open(agroup, 'w') { |file|
file.puts email
}
text = File.read(agroup)
member = text.gsub('Initial creation by publican', 'Initial creation')
puts member
File.open(agroup, 'w') { |file|
file.puts member
}
text = File.read(agroup)
org = text.gsub('Enter your organisation\'s name here.', "#{company_name}")
puts org
File.open(agroup, 'w') { |file|
file.puts org
}
text = File.read(agroup)
div = text.gsub('Enter your organisational division here.', "#{company_division}")
puts div
File.open(agroup, 'w') { |file|
file.puts div
}
所以它看起来有点复杂。也许有人可以告诉我,如何缩小代码复杂度?可悲的是,我没有早点做过这样的事情。
答案 0 :(得分:2)
可以通过如此好的重构来解决:
def self.add_result(nice_description, value_name, agroup)
text = File.read(agroup)
new_value = text.gsub(nice_description, value_name)
puts new_value
File.open(agroup, 'w') { |file|
file.puts new_value
}
def self.fix_authorgroup_work(title, name, email_business, company_name, company_division)
agroup = "#{title}/de-DE/Author_Group.xml"
namechomp = name.chomp
# @note Split the variable to the array title[*]
name = namechomp.split(' ')
firstname = name[0]
surname = name[1]
# @note Author Group: Change the default stuff to the present user
puts 'Replace the default content with the new content from the user (Authors_Group)'.color(:yellow)
add_result('Enter your first name here.', "#{firstname}", agroup)
add_result('Enter your surname here.', "#{surname}", agroup)
add_result('Enter your email address here.', "#{email_business}", agroup)
add_result('Initial creation by publican', "Initial creation", agroup)
add_result('Enter your organisation\'s name here.', "#{company_name}", agroup)
add_result('Enter your organisational division here.', "#{company_division}", agroup)
答案 1 :(得分:2)
Daniel Slater的答案很棒。
此外,您还可以通过以下方式清理您的namechomp业务:
namechomp = name.chomp
name = namechomp.split(' ')
firstname = name[0]
surname = name[1]
为:
firstname, surname = name.chomp.split(' ')
答案 2 :(得分:0)
一个好的起点是将其重组为Composed Method。