用Ruby格式化散列

mfuanj7w  于 2023-03-17  发布在  Ruby
关注(0)|答案(1)|浏览(121)

我需要以编程方式格式化一个Ruby散列,如下所示:

{
  type: "Processors::GroupRows",
  position: 1,
  config:
   {columns:
     [{strategy: "concat_uniq",
       local_column: "all_emails",
       source_column: "email"},
      {strategy: "concat_uniq",
       local_column: "all_phones",
       source_column: "phone"},
      {strategy: "count", local_column: "total_ads", source_column: "_id"},
      {strategy: "sum_int",
       local_column: "total_vacancies",
       source_column: "vacancies"}],
    group_by_column: "employer",
    select_row_columns:
     [{strategy: "maximum",
       column_type: "date",
       filter_column: "modified_at",
       insert_columns: [{source_column: "*"}]}]}
}

变成这样:

{
  type: "Processors::GroupRows",
  position: 1,
  config: {
    columns: [ # this could also be '[{' and to save the extra indent
      {
        strategy: "concat_uniq",
        local_column: "all_emails",
        source_column: "email"
      }, {
        strategy: "concat_uniq",
        local_column: "all_phones",
        source_column: "phone"
      }, {
        strategy: "count",
        local_column: "total_ads",
        source_column: "_id"
      }, {
        strategy: "sum_int",
        local_column: "total_vacancies",
        source_column: "vacancies"
      }
    ],
    group_by_column: "employer",
    select_row_columns: [
      {
        strategy: "maximum",
        column_type: "date",
        filter_column: "modified_at",
        insert_columns: [{source_column: "*"}]
      }
    ]
  }
}

我试过Rubocop,不同的格式化程序,但我总是投入大量的时间,没有结果。
非常感谢您的帮助。

esbemjvw

esbemjvw1#

到目前为止,我发现这是可行的,使用pretty_print作为格式化程序并修复输出。
它没有使用Rubocop,所以不是高度可定制的,可能会打破。

puts attrs
    .ai(indent: -2, plain: true)
    .gsub(/:([A-Za-z_]+)\s+=>\s+/, "\\1: ")
    .gsub(/},\s+{/, '}, {')

相关问题