3

以示例 ruby​​ 代码为例,如何重写/缩进它,以便下面的 ruby​​ 代码使其更具可读性并确保它适合一行,即 80-90chars?

%w(survey survey_section question_group question dependency dependency_condition answer answer_type answer_validity validation validation_condition validation_prefix validation_precludes error error_type error_level error_code style style_info style_override user user_model_name user_type).each {|m| require m }

阅读它很痛苦,因为我在整个代码库中都有这样的长数组。它需要很多水平滚动,我不喜欢那样

有什么办法可以改善这一点?

4

2 回答 2

8

空格上的%w拆分,因此您可以随时插入换行符并获得相同的结果:

dependencies = %w(survey survey_section question_group question 
  dependency dependency_condition answer answer_type answer_validity 
  validation validation_condition validation_prefix 
  validation_precludes error error_type error_level error_code 
  style style_info style_override user user_model_name user_type)

dependencies.each {|m| require m }
于 2012-05-18T13:21:01.723 回答
2

与@derekerdmann 的做法类似,我可能会使用:

%w[
  survey               survey_section       question_group       question
  dependency           dependency_condition answer               answer_type
  answer_validity      validation           validation_condition validation_prefix
  validation_precludes error                error_type           error_level       error_code
  style                style_info           style_override       user
  user_model_name      user_type
].each { |m| require m }

使用 Align 插件,在 Vim 中这样的包装和对齐很简单。

但是,更有可能的是,我会将所有要求放入一个单独的文件中并要求它,就像在 C 中使用包含文件来拉入一堆其他包含文件一样。在这种情况下,它们仍在加载中,但它们不在视线范围内。所以,在一个requirements.rb文件中,我有:

require 'answer'
require 'answer_type'
require 'answer_validity'
require 'dependency'
require 'dependency_condition'
require 'error'
require 'error_code'
require 'error_level'
require 'error_type'
require 'question'
require 'question_group'
require 'style'
require 'style_info'
require 'style_override'
require 'survey'
require 'survey_section'
require 'user'
require 'user_model_name'
require 'user_type'
require 'validation'
require 'validation_condition'
require 'validation_precludes'
require 'validation_prefix'

在我的主代码文件中,我有require_relative './requirements'.

或者,我会将列表拆分为更易于管理的分组,例如按字母顺序:

%w[ answer answer_type answer_validity ].each { |r| require r }
%w[ dependency dependency_condition ].each { |r| require r }
%w[ error error_code error_level error_type ].each { |r| require r }
%w[ question question_group ].each { |r| require r }
%w[ style style_info style_override survey survey_section ].each { |r| require r }
%w[ user user_model_name user_type ].each { |r| require r }
%w[ validation validation_condition validation_precludes validation_prefix ].each { |r| require r }

它不像我想要的那样干燥,但它更有条理和可读性。

于 2012-05-23T06:31:19.363 回答