我想知道是否有办法将CSV标头转换为正式命名,如last_name到"姓氏"。
以下是我的控制器中的代码:
def cross_mri_transfer
@reports = EmployeeEvent.where(event_type: "cross_mri_transfer")
respond_to do |format|
format.html
format.csv { send_data @reports.cmt_to_csv, filename: "cross-mri-transfer-event-#{Date.today}.csv" }
end
end
以下是模型中我方法中的代码:
def self.cmt_to_csv
attributes = %w{
employee_name
location_assignment
job_grade_position
from_institution
from_cluster
from_region
from_area
from_unit
to_institution
to_cluster
to_region
to_area
to_unit
status
initiated_by
start_date
approved_by
applied_at
}
CSV.generate(headers: true) do |csv|
csv << attributes
all.each do |employee_event|
csv << [
employee_event.employee.fullname_formal,
employee_event.location_assignment,
employee_event.job_grade_position,
employee_event.event_data[:old][:institution_name],
employee_event.event_data[:old][:cluster_name],
employee_event.event_data[:old][:region_name],
employee_event.event_data[:old][:area_name],
employee_event.event_data[:old][:unit_name],
employee_event.event_data[:new][:institution_name],
employee_event.event_data[:new][:cluster_name],
employee_event.event_data[:new][:region_name],
employee_event.event_data[:new][:area_name],
employee_event.event_data[:new][:unit_name],
employee_event.status,
employee_event.steps.where(step_type: :approve).first.performed_actor.fullname_formal.upcase,
employee_event.start_date,
employee_event.steps.where(step_type: :approve).last.performed_actor.fullname_formal.upcase,
employee_event.applied_at
]
end
end
所以继续前进有没有办法用空格替换标题下划线并大写标题的第一个字符?
答案 0 :(得分:2)
这应该很简单 - 添加行
attributes.map!(&:humanize)
如果您更喜欢结果,也可以使用:titleize
。
:humanize
分隔单词并将第一个单词的第一个字母大写;
:titleize
将单词和竖起每个单词的第一个字母分开。
这会将字符串转换为漂亮,可读的格式 - 文档:
答案 1 :(得分:1)
尝试 String#split 和 String#capitalize
> attributes.map{|e| e.split("_").map(&:capitalize).join(' ')}
#=> ["Employee Name", "Location Assignment", "Job Grade Position", "From Institution", "From Cluster", "From Region", "From Area", "From Unit", "To Institution", "To Cluster", "To Region", "To Area", "To Unit", "Status", "Initiated By", "Start Date", "Approved By", "Applied At"]
注意: String#humanize 会拆分单词,但第一个单词的首字母大写不是其他单词。例如:
> "employee_name".humanize
#=> "Employee name"
但是根据你的例子:你想要last_name
到"Last Name"
。
> "last_name".split("_").map(&:capitalize).join(' ')
#=> "Last Name"