我如何将下划线变成在Ruby在Rails上打印CSV的空间



我想知道是否有一种方法可以将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

因此,继续前进是否有某种方法可以用空格替换标题下划线并大写标题的第一个字符?

这应该很简单 - 添加行

attributes.map!(&:humanize)

如果您喜欢结果,也可以使用:titleize

:humanize将单词分开并大写了 first word的第一个字母; :titleize将单词分开,并抬高 word的第一个字母。

这将把字符串转换为一个不错的,可读的格式 - 在此处:

https://apidock.com/rails/string/humanize

https://apidock.com/rails/activeupport/inflector/titleize

尝试使用字符串#split 字符串#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"]

注意:字符串#人性化会拆分单词,但第一个单词唯一的第一个字母大写而不是其他单词。例如:

> "employee_name".humanize
#=> "Employee name"

,但根据您的EG:您要last_name"Last Name"

> "last_name".split("_").map(&:capitalize).join(' ')
#=> "Last Name"

相关内容

  • 没有找到相关文章

最新更新