Module: RailsBestPractices

Defined in:
lib/rails_best_practices.rb,
lib/rails_best_practices/version.rb,
lib/rails_best_practices/core/nil.rb,
lib/rails_best_practices/prepares.rb,
lib/rails_best_practices/core/check.rb,
lib/rails_best_practices/core/error.rb,
lib/rails_best_practices/core/models.rb,
lib/rails_best_practices/core/runner.rb,
lib/rails_best_practices/core/mailers.rb,
lib/rails_best_practices/reviews/review.rb,
lib/rails_best_practices/core/checking_visitor.rb,
lib/rails_best_practices/core/model_attributes.rb,
lib/rails_best_practices/prepares/model_prepare.rb,
lib/rails_best_practices/core/model_associations.rb,
lib/rails_best_practices/prepares/mailer_prepare.rb,
lib/rails_best_practices/prepares/schema_prepare.rb,
lib/rails_best_practices/lexicals/remove_tab_check.rb,
lib/rails_best_practices/reviews/use_observer_review.rb,
lib/rails_best_practices/reviews/law_of_demeter_review.rb,
lib/rails_best_practices/reviews/use_scope_access_review.rb,
lib/rails_best_practices/reviews/isolate_seed_data_review.rb,
lib/rails_best_practices/reviews/use_before_filter_review.rb,
lib/rails_best_practices/reviews/always_add_db_index_review.rb,
lib/rails_best_practices/reviews/use_query_attribute_review.rb,
lib/rails_best_practices/reviews/move_code_into_model_review.rb,
lib/rails_best_practices/reviews/remove_empty_helpers_review.rb,
lib/rails_best_practices/reviews/move_code_into_helper_review.rb,
lib/rails_best_practices/reviews/needless_deep_nesting_review.rb,
lib/rails_best_practices/reviews/not_use_default_route_review.rb,
lib/rails_best_practices/reviews/use_model_association_review.rb,
lib/rails_best_practices/reviews/simplify_render_in_views_review.rb,
lib/rails_best_practices/reviews/dry_bundler_in_capistrano_review.rb,
lib/rails_best_practices/reviews/move_code_into_controller_review.rb,
lib/rails_best_practices/lexicals/remove_trailing_whitespace_check.rb,
lib/rails_best_practices/reviews/move_finder_to_named_scope_review.rb,
lib/rails_best_practices/reviews/add_model_virtual_attribute_review.rb,
lib/rails_best_practices/reviews/move_model_logic_into_model_review.rb,
lib/rails_best_practices/reviews/overuse_route_customizations_review.rb,
lib/rails_best_practices/reviews/simplify_render_in_controllers_review.rb,
lib/rails_best_practices/reviews/keep_finders_on_their_own_model_review.rb,
lib/rails_best_practices/reviews/use_say_with_time_in_migrations_review.rb,
lib/rails_best_practices/reviews/replace_complex_creation_with_factory_method_review.rb,
lib/rails_best_practices/reviews/replace_instance_variable_with_local_variable_review.rb,
lib/rails_best_practices/reviews/use_multipart_alternative_as_content_type_of_email_review.rb

Overview

RailsBestPractices helps you to analyze your rails code, according to best practices on rails-bestpractices. if it finds any violatioins to best practices, it will give you some readable suggestions.

The analysis process is partitioned into two parts,

  1. prepare process, it checks only model and mailer files, do some preparations, such as remember model names and associations.

  2. review process, it checks all files, according to configuration, it really check if codes violate the best practices, if so, remember the violations.

After analyzing, output the violations.

Defined Under Namespace

Modules: Core, Lexicals, Prepares, Reviews

Constant Summary collapse

DEFAULT_CONFIG =
File.join(File.dirname(__FILE__), "..", "rails_best_practices.yml")
VERSION =
"0.9.1"

Class Attribute Summary collapse

Class Method Summary collapse

Class Attribute Details

.runner=(value) ⇒ Object (writeonly)

Sets the attribute runner

Parameters:

  • value

    the value to set the attribute runner to.



49
50
51
# File 'lib/rails_best_practices.rb', line 49

def runner=(value)
  @runner = value
end

Class Method Details

.expand_dirs_to_files(*dirs) ⇒ Array

expand all files with extenstion rb, erb, haml and builder under the dirs

Parameters:

  • dirs (Array)

    what directories to expand

Returns:

  • (Array)

    all files expanded



148
149
150
151
152
153
154
155
156
157
158
159
# File 'lib/rails_best_practices.rb', line 148

def expand_dirs_to_files *dirs
  extensions = ['rb', 'erb', 'rhtml', 'haml', 'builder']

  dirs.flatten.map { |entry|
    next unless File.exist? entry
    if File.directory? entry
      Dir[File.join(entry, '**', "*.{#{extensions.join(',')}}")]
    else
      entry
    end
  }.flatten
end

.file_ignore(files, pattern) ⇒ Array

ignore specific files.

Parameters:

  • files (Array)
  • pattern (Regexp)

    files match the pattern will be ignored

Returns:

  • (Array)

    files that not match the pattern



200
201
202
# File 'lib/rails_best_practices.rb', line 200

def file_ignore files, pattern
  files.reject { |file| file.index(pattern) }
end

.file_sort(files) ⇒ Array

sort files, models first, then mailers, and sort other files by characters.

models and mailers first as for prepare process.

Parameters:

  • files (Array)

Returns:

  • (Array)

    sorted files



168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
# File 'lib/rails_best_practices.rb', line 168

def file_sort files
  models = []
  mailers = []
  files.each do |a| 
      if a =~ Core::Check::MODEL_FILES
        models << a
      end
  end
  files.each do |a| 
      if a =~ Core::Check::MAILER_FILES
        mailers << a
      end
  end
  files.collect! do |a| 
      if a =~ Core::Check::MAILER_FILES || a =~ Core::Check::MODEL_FILES
        #nil
      else
        a
      end
  end
  files.compact!
  models.sort
  mailers.sort
  files.sort
  return models + mailers + files
end

.generate(path) ⇒ Object

generate configuration yaml file.

Parameters:

  • path (String)

    where to generate the configuration yaml file



54
55
56
57
# File 'lib/rails_best_practices.rb', line 54

def generate(path)
  @path =  path || '.'
  FileUtils.cp DEFAULT_CONFIG, File.join(@path, 'config/rails_best_practices.yml')
end

.output_html_errorsObject



223
224
225
226
227
228
229
# File 'lib/rails_best_practices.rb', line 223

def output_html_errors
  template = File.read(File.join(File.dirname(__FILE__), "..", "assets", "result.html.haml"))

  File.open("rails_best_practices_output.html", "w+") do |file|
    file.puts Haml::Engine.new(template).render(Object.new, :errors => @runner.errors, :textmate => @options["with-textmate"], :mvim => @options["with-mvim"])
  end
end

.output_terminal_errorsObject

output errors if exist.



205
206
207
208
209
210
211
212
213
# File 'lib/rails_best_practices.rb', line 205

def output_terminal_errors
  @runner.errors.each { |error| plain_output(error.to_s, 'red') }
  plain_output("\nPlease go to http://rails-bestpractices.com to see more useful Rails Best Practices.", 'green')
  if @runner.errors.empty?
    plain_output("\nNo error found. Cool!", 'green')
  else
    plain_output("\nFound #{@runner.errors.size} errors.", 'red')
  end
end

.plain_output(message, color) ⇒ Object



215
216
217
218
219
220
221
# File 'lib/rails_best_practices.rb', line 215

def plain_output(message, color)
  if @options["without-color"]
    puts message
  else
    puts message.send(color)
  end
end

.prepare_filesArray

get all files for prepare process.

Returns:

  • (Array)

    all files for prepare process



114
115
116
117
118
119
120
# File 'lib/rails_best_practices.rb', line 114

def prepare_files
  @prepare_files ||= begin
    ['app/models', 'app/mailers', 'db/schema.rb'].inject([]) { |files, name|
      files += expand_dirs_to_files(File.join(@path, name))
    }.compact
  end
end

.process(process) ⇒ Object

process lexical, prepare or reivew.

get all files for the process, analyze each file, and increment progress bar unless debug.

Parameters:

  • process (String)

    the process name, lexical, prepare or review.



103
104
105
106
107
108
109
# File 'lib/rails_best_practices.rb', line 103

def process(process)
  files = send("#{process}_files")
  files.each do |file|
    @runner.send("#{process}_file", file)
    @bar.inc unless @options['debug']
  end
end

.review_filesArray Also known as: lexical_files

get all files for review process.

Returns:

  • (Array)

    all files for review process



125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
# File 'lib/rails_best_practices.rb', line 125

def review_files
  @review_files ||= begin
    files = expand_dirs_to_files(@path)
    files = file_sort(files)
    ['vendor', 'spec', 'test', 'features'].each do |pattern|
      files = file_ignore(files, "#{pattern}/") unless @options[pattern]
    end

    # Exclude files based on exclude regexes if the option is set.
    @options[:exclude].each do |pattern|
      files = file_ignore(files, pattern)
    end

    files.compact
  end
end

.start(path, options) ⇒ Object

start checking rails codes.

there are two steps to check rails codes,

  1. prepare process, check all model and mailer files.

  2. review process, check all files.

if there are violations to rails best practices, output them.

Parameters:

  • path (String)

    the directory of rails project

  • options (Hash)


70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
# File 'lib/rails_best_practices.rb', line 70

def start(path, options)
  @path = path || '.'
  @options = options
  @options[:exclude] ||= []

  Core::Runner.base_path = @path
  @runner = Core::Runner.new
  @runner.debug = true if @options['debug']
  @runner.color = !options['without-color']

  if @runner.checks.find { |check| check.is_a? Reviews::AlwaysAddDbIndexReview } &&
     !review_files.find { |file| file.index "db\/schema.rb" }
    plain_output("AlwaysAddDbIndexReview is disabled as there is no db/schema.rb file in your rails project.", 'blue')
  end

  @bar = ProgressBar.new('Analyzing', lexical_files.size + prepare_files.size + review_files.size)
  ["lexical", "prepare", "review"].each { |process| send(:process, process) }
  @bar.finish

  if @options['format'] == 'html'
    output_html_errors
  else
    output_terminal_errors
  end
  exit @runner.errors.size
end