获取示例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 }
阅读它是痛苦的,因为我在整个代码库中都有这样的长数组。它需要很多水平滚动和我不喜欢那个
我能以任何方式改进这个吗?
答案 0 :(得分: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 }
答案 1 :(得分: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 }
它不像我想的那样干,但它更有条理和可读。