repo stringlengths 5 92 | file_url stringlengths 80 287 | file_path stringlengths 5 197 | content stringlengths 0 32.8k | language stringclasses 1
value | license stringclasses 7
values | commit_sha stringlengths 40 40 | retrieved_at stringdate 2026-01-04 15:37:27 2026-01-04 17:58:21 | truncated bool 2
classes |
|---|---|---|---|---|---|---|---|---|
grosser/parallel | https://github.com/grosser/parallel/blob/8d638d0d8e4c17dd74776557991e3aa73dfc8b07/spec/cases/with_break.rb | spec/cases/with_break.rb | # frozen_string_literal: true
require './spec/cases/helper'
$stdout.sync = true # otherwise results can go weird...
method = ENV.fetch('METHOD')
in_worker_type = :"in_#{ENV.fetch('WORKER_TYPE')}"
worker_size = (ENV['WORKER_SIZE'] || 4).to_i
ARGV.freeze # make ractor happy
class Callback
def self.call(x)
$stdout.sync = true
sleep 0.1 # so all workers get started
print x
raise Parallel::Break, *ARGV if x == 1
sleep 0.2 # so now no work gets queued before Parallel::Break is raised
x
end
end
options = { in_worker_type => worker_size }
result =
if in_worker_type == :in_ractors
Parallel.public_send(method, 1..10, options.merge(ractor: [Callback, :call]))
else
Parallel.public_send(method, 1..10, options) { |x| Callback.call x }
end
print " Parallel::Break raised - result #{result.inspect}"
| ruby | MIT | 8d638d0d8e4c17dd74776557991e3aa73dfc8b07 | 2026-01-04T15:46:55.131598Z | false |
grosser/parallel | https://github.com/grosser/parallel/blob/8d638d0d8e4c17dd74776557991e3aa73dfc8b07/spec/cases/flat_map.rb | spec/cases/flat_map.rb | # frozen_string_literal: true
require './spec/cases/helper'
result = Parallel.flat_map(['a', 'b']) do |x|
[x, [x]]
end
print result.inspect
| ruby | MIT | 8d638d0d8e4c17dd74776557991e3aa73dfc8b07 | 2026-01-04T15:46:55.131598Z | false |
grosser/parallel | https://github.com/grosser/parallel/blob/8d638d0d8e4c17dd74776557991e3aa73dfc8b07/spec/cases/finish_in_order.rb | spec/cases/finish_in_order.rb | # frozen_string_literal: true
require './spec/cases/helper'
class Callback
def self.call(item)
sleep rand * 0.01
item.is_a?(Numeric) ? "F#{item}" : item
end
end
method = ENV.fetch('METHOD')
in_worker_type = :"in_#{ENV.fetch('WORKER_TYPE')}"
$stdout.sync = true
items = [nil, false, 2, 3, 4]
finish = ->(item, index, result) { puts "finish #{item.inspect} #{index} #{result.inspect}" }
options = { in_worker_type => 4, finish: finish, finish_in_order: true }
if in_worker_type == :in_ractors
Parallel.public_send(method, items, options.merge(ractor: [Callback, :call]))
else
Parallel.public_send(method, items, options) { |item| Callback.call(item) }
end
| ruby | MIT | 8d638d0d8e4c17dd74776557991e3aa73dfc8b07 | 2026-01-04T15:46:55.131598Z | false |
grosser/parallel | https://github.com/grosser/parallel/blob/8d638d0d8e4c17dd74776557991e3aa73dfc8b07/spec/cases/helper.rb | spec/cases/helper.rb | # frozen_string_literal: true
require 'bundler/setup'
require 'parallel'
def process_diff
called_from = caller(1)[0].split(":").first # forks will have the source file in their name
cmd = "ps uxw|grep #{called_from}|wc -l"
processes_before = `#{cmd}`.to_i
yield
sleep 1
processes_after = `#{cmd}`.to_i
if processes_before == processes_after
print 'OK'
else
print "FAIL: before:#{processes_before} -- after:#{processes_after}"
end
end
| ruby | MIT | 8d638d0d8e4c17dd74776557991e3aa73dfc8b07 | 2026-01-04T15:46:55.131598Z | false |
grosser/parallel | https://github.com/grosser/parallel/blob/8d638d0d8e4c17dd74776557991e3aa73dfc8b07/spec/cases/timeout_in_threads.rb | spec/cases/timeout_in_threads.rb | # frozen_string_literal: true
require './spec/cases/helper'
require 'timeout'
Parallel.each([1], in_threads: 1) do |_i|
Timeout.timeout(0.1) { sleep 0.2 }
rescue Timeout::Error
puts "OK"
else
puts "BROKEN"
end
| ruby | MIT | 8d638d0d8e4c17dd74776557991e3aa73dfc8b07 | 2026-01-04T15:46:55.131598Z | false |
grosser/parallel | https://github.com/grosser/parallel/blob/8d638d0d8e4c17dd74776557991e3aa73dfc8b07/spec/cases/map_with_nested_arrays_and_nil.rb | spec/cases/map_with_nested_arrays_and_nil.rb | # frozen_string_literal: true
require './spec/cases/helper'
result = Parallel.map([1, 2, [3]]) do |x|
[x, x] if x != 1
end
print result.inspect
| ruby | MIT | 8d638d0d8e4c17dd74776557991e3aa73dfc8b07 | 2026-01-04T15:46:55.131598Z | false |
grosser/parallel | https://github.com/grosser/parallel/blob/8d638d0d8e4c17dd74776557991e3aa73dfc8b07/spec/cases/after_interrupt.rb | spec/cases/after_interrupt.rb | # frozen_string_literal: true
require './spec/cases/helper'
Parallel.map([1, 2], in_processes: 2) {}
puts Signal.trap(:SIGINT, "IGNORE")
| ruby | MIT | 8d638d0d8e4c17dd74776557991e3aa73dfc8b07 | 2026-01-04T15:46:55.131598Z | false |
grosser/parallel | https://github.com/grosser/parallel/blob/8d638d0d8e4c17dd74776557991e3aa73dfc8b07/spec/cases/no_gc_with_each.rb | spec/cases/no_gc_with_each.rb | # frozen_string_literal: true
require './spec/cases/helper'
Parallel.each(1..1000, in_threads: 2) do |_i|
"xxxx" * 1_000_000
end
| ruby | MIT | 8d638d0d8e4c17dd74776557991e3aa73dfc8b07 | 2026-01-04T15:46:55.131598Z | false |
grosser/parallel | https://github.com/grosser/parallel/blob/8d638d0d8e4c17dd74776557991e3aa73dfc8b07/spec/cases/each.rb | spec/cases/each.rb | # frozen_string_literal: true
require './spec/cases/helper'
$stdout.sync = true # otherwise results can go weird...
x = ['a', 'b', 'c', 'd']
result = Parallel.each(x) do |y|
sleep 0.1 if y == 'a'
end
print result * ' '
| ruby | MIT | 8d638d0d8e4c17dd74776557991e3aa73dfc8b07 | 2026-01-04T15:46:55.131598Z | false |
grosser/parallel | https://github.com/grosser/parallel/blob/8d638d0d8e4c17dd74776557991e3aa73dfc8b07/spec/cases/all_true.rb | spec/cases/all_true.rb | # frozen_string_literal: true
require './spec/cases/helper'
$stdout.sync = true # otherwise results can go weird...
results = []
[{ in_processes: 2 }, { in_threads: 2 }, { in_threads: 0 }].each do |options|
x = [nil, nil, nil, nil, nil, nil, nil, nil]
results << Parallel.all?(x, options, &:nil?)
x = [42, 42, 42, 42, 42, 42, 42, 42, 42, 42, 42]
results << Parallel.all?(x, options) do |y|
y == 42
end
# Empty array should return true
x = []
results << Parallel.all?(x, options) do |y|
y
end
end
print results.join(',')
| ruby | MIT | 8d638d0d8e4c17dd74776557991e3aa73dfc8b07 | 2026-01-04T15:46:55.131598Z | false |
grosser/parallel | https://github.com/grosser/parallel/blob/8d638d0d8e4c17dd74776557991e3aa73dfc8b07/spec/cases/filter_map.rb | spec/cases/filter_map.rb | # frozen_string_literal: true
require './spec/cases/helper'
result = Parallel.filter_map(['a', 'b', 'c']) do |x|
x if x != 'b'
end
print result.inspect
| ruby | MIT | 8d638d0d8e4c17dd74776557991e3aa73dfc8b07 | 2026-01-04T15:46:55.131598Z | false |
grosser/parallel | https://github.com/grosser/parallel/blob/8d638d0d8e4c17dd74776557991e3aa73dfc8b07/spec/cases/map_with_killed_worker_before_write.rb | spec/cases/map_with_killed_worker_before_write.rb | # frozen_string_literal: true
require './spec/cases/helper'
Parallel::Worker.class_eval do
alias_method :work_without_kill, :work
def work(*args)
Process.kill("SIGKILL", pid)
sleep 0.5
work_without_kill(*args)
end
end
begin
Parallel.map([1, 2, 3]) do |_x, _i|
Process.kill("SIGKILL", Process.pid)
end
rescue Parallel::DeadWorker
puts "DEAD"
end
| ruby | MIT | 8d638d0d8e4c17dd74776557991e3aa73dfc8b07 | 2026-01-04T15:46:55.131598Z | false |
grosser/parallel | https://github.com/grosser/parallel/blob/8d638d0d8e4c17dd74776557991e3aa73dfc8b07/spec/cases/parallel_with_detected_cpus.rb | spec/cases/parallel_with_detected_cpus.rb | # frozen_string_literal: true
require './spec/cases/helper'
x = Parallel.in_processes do
"HELLO"
end
puts x
| ruby | MIT | 8d638d0d8e4c17dd74776557991e3aa73dfc8b07 | 2026-01-04T15:46:55.131598Z | false |
grosser/parallel | https://github.com/grosser/parallel/blob/8d638d0d8e4c17dd74776557991e3aa73dfc8b07/spec/cases/parallel_map_uneven.rb | spec/cases/parallel_map_uneven.rb | # frozen_string_literal: true
require './spec/cases/helper'
Parallel.map([1, 2, 1, 2]) do |x|
sleep 2 if x == 1
end
| ruby | MIT | 8d638d0d8e4c17dd74776557991e3aa73dfc8b07 | 2026-01-04T15:46:55.131598Z | false |
grosser/parallel | https://github.com/grosser/parallel/blob/8d638d0d8e4c17dd74776557991e3aa73dfc8b07/spec/cases/progress_with_finish.rb | spec/cases/progress_with_finish.rb | # frozen_string_literal: true
require './spec/cases/helper'
sum = 0
finish = ->(_item, _index, result) { sum += result }
Parallel.map(1..50, progress: "Doing stuff", finish: finish) do
sleep 1 if $stdout.tty? # for debugging
2
end
puts sum
| ruby | MIT | 8d638d0d8e4c17dd74776557991e3aa73dfc8b07 | 2026-01-04T15:46:55.131598Z | false |
grosser/parallel | https://github.com/grosser/parallel/blob/8d638d0d8e4c17dd74776557991e3aa73dfc8b07/spec/cases/progress.rb | spec/cases/progress.rb | # frozen_string_literal: true
require './spec/cases/helper'
title = (ENV["TITLE"] == "true" ? true : "Doing stuff")
Parallel.map(1..50, progress: title) do
sleep 1 if $stdout.tty? # for debugging
end
| ruby | MIT | 8d638d0d8e4c17dd74776557991e3aa73dfc8b07 | 2026-01-04T15:46:55.131598Z | false |
grosser/parallel | https://github.com/grosser/parallel/blob/8d638d0d8e4c17dd74776557991e3aa73dfc8b07/spec/cases/with_exception.rb | spec/cases/with_exception.rb | # frozen_string_literal: true
require './spec/cases/helper'
$stdout.sync = true # otherwise results can go weird...
method = ENV.fetch('METHOD')
in_worker_type = :"in_#{ENV.fetch('WORKER_TYPE')}"
worker_size = (ENV['WORKER_SIZE'] || 4).to_i
class ParallelTestError < StandardError
end
class Callback
def self.call(x)
$stdout.sync = true
sleep 0.1 # so all workers get started
print x
raise ParallelTestError, 'foo' if x == 1
sleep 0.2 # so now no work gets queued before exception is raised
x
end
end
begin
options = { in_worker_type => worker_size }
if in_worker_type == :in_ractors
Parallel.public_send(method, 1..100, options.merge(ractor: [Callback, :call]))
else
Parallel.public_send(method, 1..100, options) { |x| Callback.call x }
end
rescue ParallelTestError
print ' raised'
end
| ruby | MIT | 8d638d0d8e4c17dd74776557991e3aa73dfc8b07 | 2026-01-04T15:46:55.131598Z | false |
grosser/parallel | https://github.com/grosser/parallel/blob/8d638d0d8e4c17dd74776557991e3aa73dfc8b07/lib/parallel.rb | lib/parallel.rb | # frozen_string_literal: true
require 'rbconfig'
require 'parallel/version'
module Parallel
Stop = Object.new.freeze
class DeadWorker < StandardError
end
class Break < StandardError
attr_reader :value
def initialize(value = nil)
super()
@value = value
end
end
class Kill < Break
end
class UndumpableException < StandardError
attr_reader :backtrace
def initialize(original)
super("#{original.class}: #{original.message}")
@backtrace = original.backtrace
end
end
class ExceptionWrapper
attr_reader :exception
def initialize(exception)
# Remove the bindings stack added by the better_errors gem,
# because it cannot be marshalled
if exception.instance_variable_defined? :@__better_errors_bindings_stack
exception.send :remove_instance_variable, :@__better_errors_bindings_stack
end
@exception =
begin
Marshal.dump(exception) && exception
rescue StandardError
UndumpableException.new(exception)
end
end
end
class Worker
attr_reader :pid, :read, :write
attr_accessor :thread
def initialize(read, write, pid)
@read = read
@write = write
@pid = pid
end
def stop
close_pipes
wait # if it goes zombie, rather wait here to be able to debug
end
# might be passed to started_processes and simultaneously closed by another thread
# when running in isolation mode, so we have to check if it is closed before closing
def close_pipes
read.close unless read.closed?
write.close unless write.closed?
end
def work(data)
begin
Marshal.dump(data, write)
rescue Errno::EPIPE
raise DeadWorker
end
result = begin
Marshal.load(read)
rescue EOFError
raise DeadWorker
end
raise result.exception if result.is_a?(ExceptionWrapper)
result
end
private
def wait
Process.wait(pid)
rescue Interrupt
# process died
end
end
class JobFactory
def initialize(source, mutex)
@lambda = (source.respond_to?(:call) && source) || queue_wrapper(source)
@source = source.to_a unless @lambda # turn Range and other Enumerable-s into an Array
@mutex = mutex
@index = -1
@stopped = false
end
def next
if producer?
# - index and item stay in sync
# - do not call lambda after it has returned Stop
item, index = @mutex.synchronize do
return if @stopped
item = @lambda.call
@stopped = (item == Stop)
return if @stopped
[item, @index += 1]
end
else
index = @mutex.synchronize { @index += 1 }
return if index >= size
item = @source[index]
end
[item, index]
end
def size
if producer?
Float::INFINITY
else
@source.size
end
end
# generate item that is sent to workers
# just index is faster + less likely to blow up with unserializable errors
def pack(item, index)
producer? ? [item, index] : index
end
# unpack item that is sent to workers
def unpack(data)
producer? ? data : [@source[data], data]
end
private
def producer?
@lambda
end
def queue_wrapper(array)
array.respond_to?(:num_waiting) && array.respond_to?(:pop) && -> { array.pop(false) }
end
end
class UserInterruptHandler
INTERRUPT_SIGNAL = :SIGINT
class << self
# kill all these pids or threads if user presses Ctrl+c
def kill_on_ctrl_c(pids, options)
@to_be_killed ||= []
old_interrupt = nil
signal = options.fetch(:interrupt_signal, INTERRUPT_SIGNAL)
if @to_be_killed.empty?
old_interrupt = trap_interrupt(signal) do
warn 'Parallel execution interrupted, exiting ...'
@to_be_killed.flatten.each { |pid| kill(pid) }
end
end
@to_be_killed << pids
yield
ensure
@to_be_killed.pop # do not kill pids that could be used for new processes
restore_interrupt(old_interrupt, signal) if @to_be_killed.empty?
end
def kill(thing)
Process.kill(:KILL, thing)
rescue Errno::ESRCH
# some linux systems already automatically killed the children at this point
# so we just ignore them not being there
end
private
def trap_interrupt(signal)
old = Signal.trap signal, 'IGNORE'
Signal.trap signal do
yield
if !old || old == "DEFAULT"
raise Interrupt
else
old.call
end
end
old
end
def restore_interrupt(old, signal)
Signal.trap signal, old
end
end
end
class << self
def in_threads(options = { count: 2 })
threads = []
count, = extract_count_from_options(options)
Thread.handle_interrupt(Exception => :never) do
Thread.handle_interrupt(Exception => :immediate) do
count.times do |i|
threads << Thread.new { yield(i) }
end
threads.map(&:value)
end
ensure
threads.each(&:kill)
end
end
def in_processes(options = {}, &block)
count, options = extract_count_from_options(options)
count ||= processor_count
map(0...count, options.merge(in_processes: count), &block)
end
def each(array, options = {}, &block)
map(array, options.merge(preserve_results: false), &block)
end
def any?(*args, &block)
raise "You must provide a block when calling #any?" if block.nil?
!each(*args) { |*a| raise Kill if block.call(*a) }
end
def all?(*args, &block)
raise "You must provide a block when calling #all?" if block.nil?
!!each(*args) { |*a| raise Kill unless block.call(*a) }
end
def each_with_index(array, options = {}, &block)
each(array, options.merge(with_index: true), &block)
end
def map(source, options = {}, &block)
options = options.dup
options[:mutex] = Mutex.new
if options[:in_processes] && options[:in_threads]
raise ArgumentError, "Please specify only one of `in_processes` or `in_threads`."
elsif RUBY_PLATFORM =~ (/java/) && !options[:in_processes]
method = :in_threads
size = options[method] || processor_count
elsif options[:in_threads]
method = :in_threads
size = options[method]
elsif options[:in_ractors]
method = :in_ractors
size = options[method]
else
method = :in_processes
if Process.respond_to?(:fork)
size = options[method] || processor_count
else
warn "Process.fork is not supported by this Ruby"
size = 0
end
end
job_factory = JobFactory.new(source, options[:mutex])
size = [job_factory.size, size].min
options[:return_results] = (options[:preserve_results] != false || !!options[:finish])
add_progress_bar!(job_factory, options)
result =
if size == 0
work_direct(job_factory, options, &block)
elsif method == :in_threads
work_in_threads(job_factory, options.merge(count: size), &block)
elsif method == :in_ractors
work_in_ractors(job_factory, options.merge(count: size), &block)
else
work_in_processes(job_factory, options.merge(count: size), &block)
end
return result.value if result.is_a?(Break)
raise result if result.is_a?(Exception)
options[:return_results] ? result : source
end
def map_with_index(array, options = {}, &block)
map(array, options.merge(with_index: true), &block)
end
def flat_map(...)
map(...).flatten(1)
end
def filter_map(...)
map(...).compact
end
# Number of physical processor cores on the current system.
def physical_processor_count
@physical_processor_count ||= begin
ppc =
case RbConfig::CONFIG["target_os"]
when /darwin[12]/
IO.popen("/usr/sbin/sysctl -n hw.physicalcpu").read.to_i
when /linux/
cores = {} # unique physical ID / core ID combinations
phy = 0
File.read("/proc/cpuinfo").scan(/^physical id.*|^core id.*/) do |ln|
if ln.start_with?("physical")
phy = ln[/\d+/]
elsif ln.start_with?("core")
cid = "#{phy}:#{ln[/\d+/]}"
cores[cid] = true unless cores[cid]
end
end
cores.count
when /mswin|mingw/
physical_processor_count_windows
else
processor_count
end
# fall back to logical count if physical info is invalid
ppc > 0 ? ppc : processor_count
end
end
# Number of processors seen by the OS or value considering CPU quota if the process is inside a cgroup,
# used for process scheduling
def processor_count
@processor_count ||= Integer(ENV['PARALLEL_PROCESSOR_COUNT'] || available_processor_count)
end
def worker_number
Thread.current[:parallel_worker_number]
end
# TODO: this does not work when doing threads in forks, so should remove and yield the number instead if needed
def worker_number=(worker_num)
Thread.current[:parallel_worker_number] = worker_num
end
private
def physical_processor_count_windows
# Get-CimInstance introduced in PowerShell 3 or earlier: https://learn.microsoft.com/en-us/previous-versions/powershell/module/cimcmdlets/get-ciminstance?view=powershell-3.0
result = run(
'powershell -command "Get-CimInstance -ClassName Win32_Processor -Property NumberOfCores ' \
'| Select-Object -Property NumberOfCores"'
)
if !result || $?.exitstatus != 0
# fallback to deprecated wmic for older systems
result = run("wmic cpu get NumberOfCores")
end
if !result || $?.exitstatus != 0
# Bail out if both commands returned something unexpected
warn "guessing pyhsical processor count"
processor_count
else
# powershell: "\nNumberOfCores\n-------------\n 4\n\n\n"
# wmic: "NumberOfCores \n\n4 \n\n\n\n"
result.scan(/\d+/).map(&:to_i).reduce(:+)
end
end
def run(command)
IO.popen(command, &:read)
rescue Errno::ENOENT
# Ignore
end
def add_progress_bar!(job_factory, options)
if (progress_options = options[:progress])
raise "Progressbar can only be used with array like items" if job_factory.size == Float::INFINITY
require 'ruby-progressbar'
if progress_options == true
progress_options = { title: "Progress" }
elsif progress_options.respond_to? :to_str
progress_options = { title: progress_options.to_str }
end
progress_options = {
total: job_factory.size,
format: '%t |%E | %B | %a'
}.merge(progress_options)
progress = ProgressBar.create(progress_options)
old_finish = options[:finish]
options[:finish] = lambda do |item, i, result|
old_finish.call(item, i, result) if old_finish
progress.increment
end
end
end
def work_direct(job_factory, options, &block)
self.worker_number = 0
results = []
exception = nil
begin
while (set = job_factory.next)
item, index = set
results << with_instrumentation(item, index, options) do
call_with_index(item, index, options, &block)
end
end
rescue StandardError
exception = $!
end
exception || results
ensure
self.worker_number = nil
end
def work_in_threads(job_factory, options, &block)
raise "interrupt_signal is no longer supported for threads" if options[:interrupt_signal]
results = []
results_mutex = Mutex.new # arrays are not thread-safe on jRuby
exception = nil
in_threads(options) do |worker_num|
self.worker_number = worker_num
# as long as there are more jobs, work on one of them
while !exception && (set = job_factory.next)
begin
item, index = set
result = with_instrumentation item, index, options do
call_with_index(item, index, options, &block)
end
results_mutex.synchronize { results[index] = result }
rescue StandardError
exception = $!
end
end
end
exception || results
end
def work_in_ractors(job_factory, options)
exception = nil
results = []
results_mutex = Mutex.new # arrays are not thread-safe on jRuby
callback = options[:ractor]
if block_given? || !callback
raise ArgumentError, "pass the code you want to execute as `ractor: [ClassName, :method_name]`"
end
# build
ractors = Array.new(options.fetch(:count)) do
Ractor.new do
loop do
got = receive
(klass, method_name), item, index = got
break if index == :break
begin
Ractor.yield [nil, klass.send(method_name, item), item, index]
rescue StandardError => e
Ractor.yield [e, nil, item, index]
end
end
end
end
# start
ractors.dup.each do |ractor|
if (set = job_factory.next)
item, index = set
instrument_start item, index, options
ractor.send [callback, item, index]
else
ractor.send([[nil, nil], nil, :break]) # stop the ractor
ractors.delete ractor
end
end
# replace with new items
while (set = job_factory.next)
item_next, index_next = set
done, (exception, result, item, index) = Ractor.select(*ractors)
if exception
ractors.delete done
break
end
instrument_finish item, index, result, options
results_mutex.synchronize { results[index] = (options[:preserve_results] == false ? nil : result) }
instrument_start item_next, index_next, options
done.send([callback, item_next, index_next])
end
# finish
ractors.each do |ractor|
(new_exception, result, item, index) = ractor.take
exception ||= new_exception
next if new_exception
instrument_finish item, index, result, options
results_mutex.synchronize { results[index] = (options[:preserve_results] == false ? nil : result) }
ractor.send([[nil, nil], nil, :break]) # stop the ractor
end
exception || results
end
def work_in_processes(job_factory, options, &blk)
workers = create_workers(job_factory, options, &blk)
results = []
results_mutex = Mutex.new # arrays are not thread-safe
exception = nil
UserInterruptHandler.kill_on_ctrl_c(workers.map(&:pid), options) do
in_threads(options) do |i|
worker = workers[i]
worker.thread = Thread.current
worked = false
begin
loop do
break if exception
item, index = job_factory.next
break unless index
if options[:isolation]
worker = replace_worker(job_factory, workers, i, options, blk) if worked
worked = true
worker.thread = Thread.current
end
begin
result = with_instrumentation item, index, options do
worker.work(job_factory.pack(item, index))
end
results_mutex.synchronize { results[index] = result } # arrays are not threads safe on jRuby
rescue StandardError => e
exception = e
if exception.is_a?(Kill)
(workers - [worker]).each do |w|
w.thread&.kill
UserInterruptHandler.kill(w.pid)
end
end
end
end
ensure
worker.stop
end
end
end
exception || results
end
def replace_worker(job_factory, workers, index, options, blk)
options[:mutex].synchronize do
# old worker is no longer used ... stop it
worker = workers[index]
worker.stop
# create a new replacement worker
running = workers - [worker]
workers[index] = worker(job_factory, options.merge(started_workers: running, worker_number: index), &blk)
end
end
def create_workers(job_factory, options, &block)
workers = []
Array.new(options[:count]).each_with_index do |_, i|
workers << worker(job_factory, options.merge(started_workers: workers, worker_number: i), &block)
end
workers
end
def worker(job_factory, options, &block)
child_read, parent_write = IO.pipe
parent_read, child_write = IO.pipe
pid = Process.fork do
self.worker_number = options[:worker_number]
begin
options.delete(:started_workers).each(&:close_pipes)
parent_write.close
parent_read.close
process_incoming_jobs(child_read, child_write, job_factory, options, &block)
ensure
child_read.close
child_write.close
end
end
child_read.close
child_write.close
Worker.new(parent_read, parent_write, pid)
end
def process_incoming_jobs(read, write, job_factory, options, &block)
until read.eof?
data = Marshal.load(read)
item, index = job_factory.unpack(data)
result =
begin
call_with_index(item, index, options, &block)
# https://github.com/rspec/rspec-support/blob/673133cdd13b17077b3d88ece8d7380821f8d7dc/lib/rspec/support.rb#L132-L140
rescue NoMemoryError, SignalException, Interrupt, SystemExit # rubocop:disable Lint/ShadowedException
raise $!
rescue Exception # # rubocop:disable Lint/RescueException
ExceptionWrapper.new($!)
end
begin
Marshal.dump(result, write)
rescue Errno::EPIPE
return # parent thread already dead
end
end
end
# options is either a Integer or a Hash with :count
def extract_count_from_options(options)
if options.is_a?(Hash)
count = options[:count]
else
count = options
options = {}
end
[count, options]
end
def call_with_index(item, index, options, &block)
args = [item]
args << index if options[:with_index]
results = block.call(*args)
if options[:return_results]
results
else
nil # avoid GC overhead of passing large results around
end
end
def with_instrumentation(item, index, options)
instrument_start(item, index, options)
result = yield
instrument_finish(item, index, result, options)
result unless options[:preserve_results] == false
end
def instrument_finish(item, index, result, options)
return unless (on_finish = options[:finish])
return instrument_finish_in_order(item, index, result, options) if options[:finish_in_order]
options[:mutex].synchronize { on_finish.call(item, index, result) }
end
# yield results in the order of the input items
# needs to use `options` to store state between executions
# needs to use `done` index since a nil result would also be valid
def instrument_finish_in_order(item, index, result, options)
options[:mutex].synchronize do
# initialize our state
options[:finish_done] ||= []
options[:finish_expecting] ||= 0 # we wait for item at index 0
# store current result
options[:finish_done][index] = [item, result]
# yield all results that are now in order
break unless index == options[:finish_expecting]
index.upto(options[:finish_done].size).each do |i|
break unless (done = options[:finish_done][i])
options[:finish_done][i] = nil # allow GC to free this item and result
options[:finish].call(done[0], i, done[1])
options[:finish_expecting] += 1
end
end
end
def instrument_start(item, index, options)
return unless (on_start = options[:start])
options[:mutex].synchronize { on_start.call(item, index) }
end
def available_processor_count
gem 'concurrent-ruby', '>= 1.3.4'
require 'concurrent-ruby'
Concurrent.available_processor_count.floor
rescue LoadError
require 'etc'
Etc.nprocessors
end
end
end
| ruby | MIT | 8d638d0d8e4c17dd74776557991e3aa73dfc8b07 | 2026-01-04T15:46:55.131598Z | false |
grosser/parallel | https://github.com/grosser/parallel/blob/8d638d0d8e4c17dd74776557991e3aa73dfc8b07/lib/parallel/version.rb | lib/parallel/version.rb | # frozen_string_literal: true
module Parallel
VERSION = Version = '1.27.0' # rubocop:disable Naming/ConstantName
end
| ruby | MIT | 8d638d0d8e4c17dd74776557991e3aa73dfc8b07 | 2026-01-04T15:46:55.131598Z | false |
flyerhzm/rails_best_practices | https://github.com/flyerhzm/rails_best_practices/blob/2ef40880d12ff8ed5f516871133ec569df03b192/spec/spec_helper.rb | spec/spec_helper.rb | # frozen_string_literal: true
$LOAD_PATH.unshift(File.dirname(__FILE__))
$LOAD_PATH.unshift(File.join(File.dirname(__FILE__), '..', 'lib'))
require 'rspec'
require 'rails_best_practices'
require 'coveralls'
Coveralls.wear!
RSpec.configure do |config|
config.after do
RailsBestPractices::Prepares.clear
end
config.filter_run focus: true
config.run_all_when_everything_filtered = true
end
| ruby | MIT | 2ef40880d12ff8ed5f516871133ec569df03b192 | 2026-01-04T15:47:01.660067Z | false |
flyerhzm/rails_best_practices | https://github.com/flyerhzm/rails_best_practices/blob/2ef40880d12ff8ed5f516871133ec569df03b192/spec/fixtures/lib/rails_best_practices/plugins/reviews/not_use_rails_root_review.rb | spec/fixtures/lib/rails_best_practices/plugins/reviews/not_use_rails_root_review.rb | # frozen_string_literal: true
require 'rails_best_practices/reviews/review'
module RailsBestPractices
module Plugins
module Reviews
class NotUseRailsRootReview < RailsBestPractices::Reviews::Review; end
end
end
end
| ruby | MIT | 2ef40880d12ff8ed5f516871133ec569df03b192 | 2026-01-04T15:47:01.660067Z | false |
flyerhzm/rails_best_practices | https://github.com/flyerhzm/rails_best_practices/blob/2ef40880d12ff8ed5f516871133ec569df03b192/spec/rails_best_practices/analyzer_spec.rb | spec/rails_best_practices/analyzer_spec.rb | # frozen_string_literal: true
require 'spec_helper'
require 'tmpdir'
module RailsBestPractices
describe Analyzer do
subject { described_class.new('.') }
describe '::new' do
it 'expands a relative path to an absolute' do
expect(subject.path).to eq File.expand_path('.')
end
end
describe 'expand_dirs_to_files' do
it 'expands all files in spec directory' do
dir = File.dirname(__FILE__)
expect(subject.expand_dirs_to_files(dir)).to be_include(dir + '/analyzer_spec.rb')
end
end
describe 'file_sort' do
it 'gets models first, mailers, helpers and then others' do
files = [
'app/controllers/users_controller.rb',
'app/mailers/user_mailer.rb',
'app/helpers/users_helper.rb',
'app/models/user.rb',
'app/views/users/index.html.haml',
'app/views/users/show.html.slim',
'lib/user.rb'
]
expect(subject.file_sort(files)).to eq(
[
'app/models/user.rb',
'app/mailers/user_mailer.rb',
'app/helpers/users_helper.rb',
'app/controllers/users_controller.rb',
'app/views/users/index.html.haml',
'app/views/users/show.html.slim',
'lib/user.rb'
]
)
end
end
describe 'file_ignore' do
before do
@all = [
'app/controllers/users_controller.rb',
'app/mailers/user_mailer.rb',
'app/models/user.rb',
'app/views/users/index.html.haml',
'app/views/users/show.html.slim',
'lib/user.rb'
]
@filtered = [
'app/controllers/users_controller.rb',
'app/mailers/user_mailer.rb',
'app/models/user.rb',
'app/views/users/index.html.haml',
'app/views/users/show.html.slim'
]
end
it 'ignores lib' do
expect(subject.file_ignore(@all, 'lib/')).to eq(@filtered)
end
it 'ignores regexp patterns' do
expect(subject.file_ignore(@all, /lib/)).to eq(@filtered)
end
end
describe 'output' do
subject { described_class.new('.', 'format' => format) }
before do
allow(subject).to receive(:output_terminal_errors)
allow(subject).to receive(:output_html_errors)
allow(subject).to receive(:output_yaml_errors)
allow(subject).to receive(:output_xml_errors)
subject.output
end
context 'when format is not set' do
let(:format) { nil }
it 'runs text output' do
expect(subject).to have_received(:output_terminal_errors)
end
end
context 'when format is yaml' do
let(:format) { 'yaml' }
it 'runs yaml output' do
expect(subject).to have_received(:output_yaml_errors)
end
end
context 'when format is html' do
let(:format) { 'html' }
it 'runs html output' do
expect(subject).to have_received(:output_html_errors)
end
end
context 'when format is xml' do
let(:format) { 'xml' }
it 'runs xml output' do
expect(subject).to have_received(:output_xml_errors)
end
end
end
describe 'output_terminal_errors' do
it 'outputs errors in terminal' do
check1 = Reviews::LawOfDemeterReview.new
check2 = Reviews::UseQueryAttributeReview.new
runner = Core::Runner.new(reviews: [check1, check2])
check1.add_error 'law of demeter', 'app/models/user.rb', 10
check2.add_error 'use query attribute', 'app/models/post.rb', 100
subject.runner = runner
subject.instance_variable_set('@options', 'without-color' => false)
$origin_stdout = $stdout
$stdout = StringIO.new
subject.output_terminal_errors
result = $stdout.string
$stdout = $origin_stdout
expect(result).to eq(
[
"\e[31mapp/models/user.rb:10 - law of demeter\e[0m",
"\e[31mapp/models/post.rb:100 - use query attribute\e[0m",
"\e[32m\nPlease go to https://rails-bestpractices.com to see more useful Rails Best Practices.\e[0m",
"\e[31m\nFound 2 warnings.\e[0m"
].join("\n") + "\n"
)
end
end
describe 'output_json_errors' do
let(:output_file) { 'rails_best_practices_output.json' }
subject do
described_class.new('.', 'format' => 'json', 'output-file' => output_file)
end
let(:check1) { Reviews::LawOfDemeterReview.new }
let(:check2) { Reviews::UseQueryAttributeReview.new }
let(:runner) { Core::Runner.new(reviews: [check1, check2]) }
let(:result) { File.read(output_file) }
before do
check1.add_error('law of demeter', 'app/models/user.rb', 10)
check2.add_error('use query attribute', 'app/models/post.rb', 100)
subject.runner = runner
subject.output
end
after do
File.delete(output_file) if File.exist?(output_file)
end
it 'saves output as json into output file' do
expect(result).to eq '[{"filename":"app/models/user.rb","line_number":"10","message":"law of demeter"},{"filename":"app/models/post.rb","line_number":"100","message":"use query attribute"}]'
end
end
describe 'parse_files' do
it 'does not filter out all files when the path contains "vendor"' do
Dir.mktmpdir do |random_dir|
Dir.mkdir(File.join(random_dir, 'vendor'))
Dir.mkdir(File.join(random_dir, 'vendor', 'my_project'))
File.open(File.join(random_dir, 'vendor', 'my_project', 'my_file.rb'), 'w') { |file| file << 'woot' }
analyzer = described_class.new(File.join(random_dir, 'vendor', 'my_project'))
expect(analyzer.parse_files).to be_include File.join(random_dir, 'vendor', 'my_project', 'my_file.rb')
end
end
it 'does not filter out all files when the path contains "spec"' do
Dir.mktmpdir do |random_dir|
Dir.mkdir(File.join(random_dir, 'spec'))
Dir.mkdir(File.join(random_dir, 'spec', 'my_project'))
File.open(File.join(random_dir, 'spec', 'my_project', 'my_file.rb'), 'w') { |file| file << 'woot' }
analyzer = described_class.new(File.join(random_dir, 'spec', 'my_project'))
expect(analyzer.parse_files).to be_include File.join(random_dir, 'spec', 'my_project', 'my_file.rb')
end
end
it 'does not filter out all files when the path contains "test"' do
Dir.mktmpdir do |random_dir|
Dir.mkdir(File.join(random_dir, 'test'))
Dir.mkdir(File.join(random_dir, 'test', 'my_project'))
File.open(File.join(random_dir, 'test', 'my_project', 'my_file.rb'), 'w') { |file| file << 'woot' }
analyzer = described_class.new(File.join(random_dir, 'test', 'my_project'))
expect(analyzer.parse_files).to be_include File.join(random_dir, 'test', 'my_project', 'my_file.rb')
end
end
it 'does not filter out all files when the path contains "features"' do
Dir.mktmpdir do |random_dir|
Dir.mkdir(File.join(random_dir, 'test'))
Dir.mkdir(File.join(random_dir, 'test', 'my_project'))
File.open(File.join(random_dir, 'test', 'my_project', 'my_file.rb'), 'w') { |file| file << 'woot' }
analyzer = described_class.new(File.join(random_dir, 'test', 'my_project'))
expect(analyzer.parse_files).to be_include File.join(random_dir, 'test', 'my_project', 'my_file.rb')
end
end
it 'does not filter out all files when the path contains "tmp"' do
Dir.mktmpdir do |random_dir|
Dir.mkdir(File.join(random_dir, 'tmp'))
Dir.mkdir(File.join(random_dir, 'tmp', 'my_project'))
File.open(File.join(random_dir, 'tmp', 'my_project', 'my_file.rb'), 'w') { |file| file << 'woot' }
analyzer = described_class.new(File.join(random_dir, 'tmp', 'my_project'))
expect(analyzer.parse_files).to be_include File.join(random_dir, 'tmp', 'my_project', 'my_file.rb')
end
end
end
end
end
| ruby | MIT | 2ef40880d12ff8ed5f516871133ec569df03b192 | 2026-01-04T15:47:01.660067Z | false |
flyerhzm/rails_best_practices | https://github.com/flyerhzm/rails_best_practices/blob/2ef40880d12ff8ed5f516871133ec569df03b192/spec/rails_best_practices/reviews/always_add_db_index_review_spec.rb | spec/rails_best_practices/reviews/always_add_db_index_review_spec.rb | # frozen_string_literal: true
require 'spec_helper'
module RailsBestPractices
module Reviews
describe AlwaysAddDbIndexReview do
let(:runner) { Core::Runner.new(reviews: described_class.new) }
it 'alwayses add db index' do
content = <<-EOF
ActiveRecord::Schema.define(version: 20100603080629) do
create_table "comments", force: true do |t|
t.string "content"
t.integer "post_id"
t.integer "user_id"
end
create_table "posts", force: true do |t|
end
create_table "users", force: true do |t|
end
end
EOF
runner.review('db/schema.rb', content)
runner.after_review
expect(runner.errors.size).to eq(2)
expect(runner.errors[0].to_s).to eq('db/schema.rb:2 - always add db index (comments => [post_id])')
expect(runner.errors[1].to_s).to eq('db/schema.rb:2 - always add db index (comments => [user_id])')
end
it 'alwayses add db index with polymorphic foreign key' do
content = <<-EOF
ActiveRecord::Schema.define(version: 20100603080629) do
create_table "versions", force: true do |t|
t.integer "versioned_id"
t.string "versioned_type"
t.string "tag"
end
end
EOF
runner.review('db/schema.rb', content)
runner.after_review
expect(runner.errors.size).to eq(1)
expect(runner.errors[0].to_s).to eq(
'db/schema.rb:2 - always add db index (versions => [versioned_id, versioned_type])'
)
end
it 'alwayses add db index with polymorphic foreign key and _type is defined before _id' do
content = <<-EOF
ActiveRecord::Schema.define(version: 20100603080629) do
create_table "versions", force: true do |t|
t.string "versioned_type"
t.integer "versioned_id"
t.string "tag"
end
end
EOF
runner.review('db/schema.rb', content)
runner.after_review
expect(runner.errors.size).to eq(1)
expect(runner.errors[0].to_s).to eq(
'db/schema.rb:2 - always add db index (versions => [versioned_id, versioned_type])'
)
end
it 'alwayses add db index with single index, but without polymorphic foreign key' do
content = <<-EOF
ActiveRecord::Schema.define(version: 20100603080629) do
create_table "taggings", force: true do |t|
t.integer "tag_id"
t.integer "taggable_id"
t.string "taggable_type"
end
create_table "tags", force: true do |t|
end
add_index "taggings", ["tag_id"], name: "index_taggings_on_tag_id"
end
EOF
runner.review('db/schema.rb', content)
runner.after_review
expect(runner.errors.size).to eq(1)
expect(runner.errors[0].to_s).to eq(
'db/schema.rb:2 - always add db index (taggings => [taggable_id, taggable_type])'
)
end
it 'alwayses add db index with polymorphic foreign key, but without single index' do
content = <<-EOF
ActiveRecord::Schema.define(version: 20100603080629) do
create_table "taggings", force: true do |t|
t.integer "tag_id"
t.integer "taggable_id"
t.string "taggable_type"
end
create_table "tags", force: true do |t|
end
add_index "taggings", ["taggable_id", "taggable_type"], name: "index_taggings_on_taggable_id_and_taggable_type"
end
EOF
runner.review('db/schema.rb', content)
runner.after_review
expect(runner.errors.size).to eq(1)
expect(runner.errors[0].to_s).to eq('db/schema.rb:2 - always add db index (taggings => [tag_id])')
end
it 'alwayses add db index only _id without non related _type column' do
content = <<-EOF
ActiveRecord::Schema.define(version: 20100603080629) do
create_table "websites", force: true do |t|
t.integer "user_id"
t.string "icon_file_name"
t.integer "icon_file_size"
t.string "icon_content_type"
end
create_table "users", force: true do |t|
end
end
EOF
runner.review('db/schema.rb', content)
runner.after_review
expect(runner.errors.size).to eq(1)
expect(runner.errors[0].to_s).to eq('db/schema.rb:2 - always add db index (websites => [user_id])')
end
it 'does not always add db index with column has no id' do
content = <<-EOF
ActiveRecord::Schema.define(version: 20100603080629) do
create_table "comments", force: true do |t|
t.string "content"
t.integer "position"
end
end
EOF
runner.review('db/schema.rb', content)
runner.after_review
expect(runner.errors.size).to eq(0)
end
it 'does not always add db index with add_index' do
content = <<-EOF
ActiveRecord::Schema.define(version: 20100603080629) do
create_table "comments", force: true do |t|
t.string "content"
t.integer "post_id"
t.integer "user_id"
end
create_table "posts", force: true do |t|
end
create_table "users", force: true do |t|
end
add_index "comments", ["post_id"], name: "index_comments_on_post_id"
add_index "comments", ["user_id"], name: "index_comments_on_user_id"
end
EOF
runner.review('db/schema.rb', content)
runner.after_review
expect(runner.errors.size).to eq(0)
end
it 'does not always add db index with t.index' do
# e.g. schema_plus creates indices like this https://github.com/lomba/schema_plus
content = <<-EOF
ActiveRecord::Schema.define(version: 20100603080629) do
create_table "comments", force: true do |t|
t.string "content"
t.integer "post_id"
t.index ["post_id"], :name => "index_comments_on_post_id"
end
create_table "posts", force: true do |t|
end
end
EOF
runner.review('db/schema.rb', content)
runner.after_review
expect(runner.errors.size).to eq(0)
end
it 'does not always add db index with only _type column' do
content = <<-EOF
ActiveRecord::Schema.define(version: 20100603080629) do
create_table "versions", force: true do |t|
t.string "versioned_type"
end
end
EOF
runner.review('db/schema.rb', content)
runner.after_review
expect(runner.errors.size).to eq(0)
end
it 'does not always add db index with multi-column index' do
content = <<-EOF
ActiveRecord::Schema.define(version: 20100603080629) do
create_table "versions", force: true do |t|
t.integer "versioned_id"
t.string "versioned_type"
t.string "tag"
end
add_index "versions", ["versioned_id", "versioned_type"], name: "index_versions_on_versioned_id_and_versioned_type"
end
EOF
runner.review('db/schema.rb', content)
runner.after_review
expect(runner.errors.size).to eq(0)
end
it 'does not always add db index if there is an index contains more columns' do
content = <<-EOF
ActiveRecord::Schema.define(version: 20100603080629) do
create_table "taggings", force: true do |t|
t.integer "taggable_id"
t.string "taggable_type"
t.string "context"
end
add_index "taggings", ["taggable_id", "taggable_type", "context"], name: "index_taggings_on_taggable_id_and_taggable_type_and_context"
end
EOF
runner.review('db/schema.rb', content)
runner.after_review
expect(runner.errors.size).to eq(0)
end
it 'does not always add db index if two indexes for polymorphic association' do
content = <<-EOF
ActiveRecord::Schema.define(version: 20100603080629) do
create_table "taggings", force: true do |t|
t.integer "tagger_id"
t.string "tagger_type"
t.datetime "created_at"
end
add_index "taggings", ["tagger_id"], name: "index_taggings_on_tagger_id"
add_index "taggings", ["tagger_type"], name: "index_taggings_on_tagger_type"
end
EOF
runner.review('db/schema.rb', content)
runner.after_review
expect(runner.errors.size).to eq(0)
end
it 'does not always add db index if table does not exist' do
content = <<-EOF
ActiveRecord::Schema.define(version: 20100603080629) do
create_table "comments", force: true do |t|
t.integer "post_id"
end
end
EOF
runner.review('db/schema.rb', content)
runner.after_review
expect(runner.errors.size).to eq(0)
end
it 'alwayses add db index if association_name is different to foreign_key' do
content = <<-EOF
class Comment < ActiveRecord::Base
belongs_to :commentor, class_name: "User"
end
EOF
runner.prepare('app/models/comment.rb', content)
content = <<-EOF
class User < ActiveRecord::Base
end
EOF
runner.prepare('app/models/user.rb', content)
content = <<-EOF
ActiveRecord::Schema.define(version: 20100603080629) do
create_table "comments", force: true do |t|
t.integer "commentor_id"
end
create_table "users", force: true do |t|
end
end
EOF
runner.review('db/schema.rb', content)
runner.after_review
expect(runner.errors.size).to eq(1)
expect(runner.errors[0].to_s).to eq('db/schema.rb:2 - always add db index (comments => [commentor_id])')
end
it 'does not check ignored files' do
runner = Core::Runner.new(reviews: described_class.new(ignored_files: %r{db/schema}))
content = <<-EOF
ActiveRecord::Schema.define(version: 20100603080629) do
create_table "comments", force: true do |t|
t.string "content"
t.integer "post_id"
t.integer "user_id"
end
create_table "posts", force: true do |t|
end
create_table "users", force: true do |t|
end
end
EOF
runner.review('db/schema.rb', content)
runner.after_review
expect(runner.errors.size).to eq(0)
end
it 'detects index option in column creation' do
content = <<-EOF
ActiveRecord::Schema.define(version: 20100603080629) do
create_table "comments", force: true do |t|
t.string "content"
t.integer "post_id", index: true
t.string "user_id", index: { unique: true }
t.integer "image_id", index: false
t.integer "link_id"
end
create_table "posts", force: true do |t|
end
create_table "users", id: :string, force: true do |t|
end
create_table "images", force: true do |t|
end
create_table "links", force: true do |t|
end
end
EOF
runner.review('db/schema.rb', content)
runner.after_review
expect(runner.errors.size).to eq(2)
expect(runner.errors[0].to_s).to eq('db/schema.rb:2 - always add db index (comments => [image_id])')
expect(runner.errors[1].to_s).to eq('db/schema.rb:2 - always add db index (comments => [link_id])')
end
end
end
end
| ruby | MIT | 2ef40880d12ff8ed5f516871133ec569df03b192 | 2026-01-04T15:47:01.660067Z | false |
flyerhzm/rails_best_practices | https://github.com/flyerhzm/rails_best_practices/blob/2ef40880d12ff8ed5f516871133ec569df03b192/spec/rails_best_practices/reviews/keep_finders_on_their_own_model_review_spec.rb | spec/rails_best_practices/reviews/keep_finders_on_their_own_model_review_spec.rb | # frozen_string_literal: true
require 'spec_helper'
module RailsBestPractices
module Reviews
describe KeepFindersOnTheirOwnModelReview do
let(:runner) { Core::Runner.new(reviews: described_class.new) }
it 'keeps finders on thier own model' do
content = <<-EOF
class Post < ActiveRecord::Base
has_many :comments
def find_valid_comments
self.comment.find(:all, conditions: { is_spam: false },
limit: 10)
end
end
EOF
runner.review('app/models/post.rb', content)
expect(runner.errors.size).to eq(1)
expect(runner.errors[0].to_s).to eq('app/models/post.rb:5 - keep finders on their own model')
end
it 'keeps finders on thier own model with all method' do
content = <<-EOF
class Post < ActiveRecord::Base
has_many :comments
def find_valid_comments
self.comment.all(conditions: { is_spam: false },
limit: 10)
end
end
EOF
runner.review('app/models/post.rb', content)
expect(runner.errors.size).to eq(1)
expect(runner.errors[0].to_s).to eq('app/models/post.rb:5 - keep finders on their own model')
end
it 'does not keep finders on thier own model with self finder' do
content = <<-EOF
class Post < ActiveRecord::Base
has_many :comments
def find_valid_comments
self.find(:all, conditions: { is_spam: false },
limit: 10)
end
end
EOF
runner.review('app/models/post.rb', content)
expect(runner.errors.size).to eq(0)
end
it 'does not keep finders on thier own model with own finder' do
content = <<-EOF
class Post < ActiveRecord::Base
has_many :comments
def find_valid_comments
Post.find(:all, conditions: { is_spam: false },
limit: 10)
end
end
EOF
runner.review('app/models/post.rb', content)
expect(runner.errors.size).to eq(0)
end
it 'does not keep finders on their own model without finder' do
content = <<-EOF
class Post < ActiveRecord::Base
has_many :comments
def find_valid_comments
self.comments.destroy_all
end
end
EOF
runner.review('app/models/post.rb', content)
expect(runner.errors.size).to eq(0)
end
it 'does not keep finders on their own model with ruby Array#find' do
content = <<-EOF
class Post < ActiveRecord::Base
has_many :comments
def active_comments
self.comments.find {|comment| comment.status == 'active'}
end
end
EOF
runner.review('app/models/post.rb', content)
expect(runner.errors.size).to eq(0)
end
it 'does not check ignored files' do
runner = Core::Runner.new(reviews: described_class.new(ignored_files: %r{app/models/post\.rb}))
content = <<-EOF
class Post < ActiveRecord::Base
has_many :comments
def find_valid_comments
self.comment.find(:all, conditions: { is_spam: false },
limit: 10)
end
end
EOF
runner.review('app/models/post.rb', content)
expect(runner.errors.size).to eq(0)
end
end
end
end
| ruby | MIT | 2ef40880d12ff8ed5f516871133ec569df03b192 | 2026-01-04T15:47:01.660067Z | false |
flyerhzm/rails_best_practices | https://github.com/flyerhzm/rails_best_practices/blob/2ef40880d12ff8ed5f516871133ec569df03b192/spec/rails_best_practices/reviews/simplify_render_in_controllers_review_spec.rb | spec/rails_best_practices/reviews/simplify_render_in_controllers_review_spec.rb | # frozen_string_literal: true
require 'spec_helper'
module RailsBestPractices
module Reviews
describe SimplifyRenderInControllersReview do
let(:runner) { Core::Runner.new(reviews: described_class.new) }
it 'simplifies render action view' do
content = <<-EOF
def edit
render action: :edit
end
EOF
runner.review('app/controllers/posts_controller.rb', content)
expect(runner.errors.size).to eq(1)
expect(runner.errors[0].to_s).to eq('app/controllers/posts_controller.rb:2 - simplify render in controllers')
end
it "simplifies render actions's template" do
content = <<-EOF
def edit
render template: 'books/edit'
end
EOF
runner.review('app/controllers/posts_controller.rb', content)
expect(runner.errors.size).to eq(1)
expect(runner.errors[0].to_s).to eq('app/controllers/posts_controller.rb:2 - simplify render in controllers')
end
it 'simplifies render an arbitrary file' do
content = <<-EOF
def edit
render file: '/path/to/rails/app/views/books/edit'
end
EOF
runner.review('app/controllers/posts_controller.rb', content)
expect(runner.errors.size).to eq(1)
expect(runner.errors[0].to_s).to eq('app/controllers/posts_controller.rb:2 - simplify render in controllers')
end
it 'does not simplify render action view' do
content = <<-EOF
render :edit
EOF
runner.review('app/controllers/posts_controller', content)
expect(runner.errors.size).to eq(0)
end
it "does not simplify render actions's template" do
content = <<-EOF
def edit
render 'books/edit'
end
EOF
runner.review('app/controllers/posts_controller.rb', content)
expect(runner.errors.size).to eq(0)
end
it 'does not simplify render an arbitrary file' do
content = <<-EOF
def edit
render '/path/to/rails/app/views/books/edit'
end
EOF
runner.review('app/controllers/posts_controller.rb', content)
expect(runner.errors.size).to eq(0)
end
it 'does not check ignored files' do
runner = Core::Runner.new(reviews: described_class.new(ignored_files: /posts_controller/))
content = <<-EOF
def edit
render action: :edit
end
EOF
runner.review('app/controllers/posts_controller.rb', content)
expect(runner.errors.size).to eq(0)
end
end
end
end
| ruby | MIT | 2ef40880d12ff8ed5f516871133ec569df03b192 | 2026-01-04T15:47:01.660067Z | false |
flyerhzm/rails_best_practices | https://github.com/flyerhzm/rails_best_practices/blob/2ef40880d12ff8ed5f516871133ec569df03b192/spec/rails_best_practices/reviews/use_multipart_alternative_as_content_type_of_email_review_spec.rb | spec/rails_best_practices/reviews/use_multipart_alternative_as_content_type_of_email_review_spec.rb | # frozen_string_literal: true
require 'spec_helper'
module RailsBestPractices
module Reviews
describe UseMultipartAlternativeAsContentTypeOfEmailReview do
let(:runner) { Core::Runner.new(prepares: Prepares::GemfilePrepare.new, reviews: described_class.new) }
before { allow(Core::Runner).to receive(:base_path).and_return('.') }
def mock_email_files(entry_files)
allow(Dir).to receive(:entries).with('./app/views/project_mailer').and_return(entry_files)
end
before do
content = <<~EOF
GEM
remote: https://rubygems.org
specs:
rails (3.2.13)
actionmailer (= 3.2.13)
actionpack (= 3.2.13)
activerecord (= 3.2.13)
activeresource (= 3.2.13)
activesupport (= 3.2.13)
bundler (~> 1.0)
railties (= 3.2.13)
EOF
runner.prepare('Gemfile.lock', content)
end
context 'project_mailer' do
let(:content) do
<<-EOF
class ProjectMailer < ActionMailer::Base
def send_email(email)
receiver email.receiver
from email.from
recipients email.recipients
sent_on Time.now
body email: email
end
end
EOF
end
context 'erb' do
it 'uses mulipart/alternative as content_type of email' do
mock_email_files(['send_email.html.erb'])
runner.review('app/mailers/project_mailer.rb', content)
expect(runner.errors.size).to eq(1)
expect(runner.errors[0].to_s).to eq(
'app/mailers/project_mailer.rb:2 - use multipart/alternative as content_type of email'
)
end
it 'does not use multiple/alternative as content_type of email when only plain text' do
mock_email_files(['send_email.text.erb'])
runner.review('app/mailers/project_mailer.rb', content)
expect(runner.errors.size).to eq(0)
end
it 'does not use multipart/alternative as content_type of email' do
mock_email_files(['send_email.text.erb', 'send_email.html.erb'])
runner.review('app/mailers/project_mailer.rb', content)
expect(runner.errors.size).to eq(0)
end
end
context 'haml' do
it 'uses mulipart/alternative as content_type of email' do
mock_email_files(['send_email.html.haml'])
runner.review('app/mailers/project_mailer.rb', content)
expect(runner.errors.size).to eq(1)
expect(runner.errors[0].to_s).to eq(
'app/mailers/project_mailer.rb:2 - use multipart/alternative as content_type of email'
)
end
it 'does not use multiple/alternative as content_type of email when only plain text' do
mock_email_files(['send_email.text.haml'])
runner.review('app/mailers/project_mailer.rb', content)
expect(runner.errors.size).to eq(0)
end
it 'does not use multipart/alternative as content_type of email' do
mock_email_files(['send_email.html.haml', 'send_email.text.haml'])
runner.review('app/mailers/project_mailer.rb', content)
expect(runner.errors.size).to eq(0)
end
it 'does not use multipart/alternative as content_type of email with text locale' do
mock_email_files(['send_email.html.haml', 'send_email.de.text.haml'])
runner.review('app/mailers/project_mailer.rb', content)
expect(runner.errors.size).to eq(0)
end
it 'does not use multipart/alternative as content_type of email with html locale' do
mock_email_files(['send_email.de.html.haml', 'send_email.text.haml'])
runner.review('app/mailers/project_mailer.rb', content)
expect(runner.errors.size).to eq(0)
end
end
context 'haml/erb mix' do
it 'does not suggest using multipart/alternative when mixing html.haml and text.erb' do
mock_email_files(['send_email.html.haml', 'send_email.text.erb'])
runner.review('app/mailers/project_mailer.rb', content)
expect(runner.errors.size).to eq(0)
mock_email_files(['send_email.html.erb', 'send_email.text.haml'])
runner.review('app/mailers/project_mailer.rb', content)
expect(runner.errors.size).to eq(0)
end
end
it 'does not check ignored files' do
runner = Core::Runner.new(reviews: described_class.new(ignored_files: /project_mailer/))
mock_email_files(['send_email.html.haml'])
runner.review('app/mailers/project_mailer.rb', content)
expect(runner.errors.size).to eq(0)
end
end
end
end
end
| ruby | MIT | 2ef40880d12ff8ed5f516871133ec569df03b192 | 2026-01-04T15:47:01.660067Z | false |
flyerhzm/rails_best_practices | https://github.com/flyerhzm/rails_best_practices/blob/2ef40880d12ff8ed5f516871133ec569df03b192/spec/rails_best_practices/reviews/check_save_return_value_review_spec.rb | spec/rails_best_practices/reviews/check_save_return_value_review_spec.rb | # frozen_string_literal: true
require 'spec_helper'
module RailsBestPractices
module Reviews
describe CheckSaveReturnValueReview do
let(:runner) { Core::Runner.new(reviews: described_class.new) }
describe 'check_save_return_value' do
it 'warns you if you fail to check save return value' do
content = <<-EOF
def my_method
post = Posts.new do |p|
p.title = "foo"
end
post.save
end
EOF
runner.review('app/helpers/posts_helper.rb', content)
expect(runner.errors.size).to eq(1)
expect(runner.errors[0].to_s).to eq(
"app/helpers/posts_helper.rb:5 - check 'save' return value or use 'save!'"
)
end
it 'allows save return value assigned to var' do
content = <<-EOF
def my_method
post = Posts.new do |p|
p.title = "foo"
end
check_this_later = post.save
end
EOF
runner.review('app/helpers/posts_helper.rb', content)
expect(runner.errors.size).to eq(0)
end
it 'allows save return value used in if' do
content = <<-EOF
def my_method
post = Posts.new do |p|
p.title = "foo"
end
if post.save
"OK"
else
raise "could not save"
end
end
EOF
runner.review('app/helpers/posts_helper.rb', content)
expect(runner.errors.size).to eq(0)
end
it 'allows save return value used in elsif' do
content = <<-EOF
def my_method
post = Posts.new do |p|
p.title = "foo"
end
if current_user
"YES"
elsif post.save
"OK"
else
raise "could not save"
end
end
EOF
runner.review('app/helpers/posts_helper.rb', content)
expect(runner.errors.size).to eq(0)
end
it 'allows save return value used in unless' do
content = <<-EOF
def my_method
unless @post.save
raise "could not save"
end
end
EOF
runner.review('app/helpers/posts_helper.rb', content)
expect(runner.errors.size).to eq(0)
end
it 'allows save return value used in if_mod' do
content = <<-EOF
def my_method
post = Posts.new do |p|
p.title = "foo"
end
"OK" if post.save
end
EOF
runner.review('app/helpers/posts_helper.rb', content)
expect(runner.errors.size).to eq(0)
end
it 'allows save return value used in unless_mod' do
content = <<-EOF
def my_method
post = Posts.new do |p|
p.title = "foo"
end
"NO" unless post.save
end
EOF
runner.review('app/helpers/posts_helper.rb', content)
expect(runner.errors.size).to eq(0)
end
it 'allows save return value used in unless with &&' do
content = <<-EOF
def my_method
unless some_method(1) && other_method(2) && @post.save
raise "could not save"
end
end
EOF
runner.review('app/helpers/posts_helper.rb', content)
expect(runner.errors.size).to eq(0)
end
it 'allows save!' do
content = <<-EOF
def my_method
post = Posts.new do |p|
p.title = "foo"
end
post.save!
end
EOF
runner.review('app/helpers/posts_helper.rb', content)
expect(runner.errors.size).to eq(0)
end
it 'warns you if you fail to check update_attributes return value' do
content = <<-EOF
def my_method
@post.update_attributes params
end
EOF
runner.review('app/helpers/posts_helper.rb', content)
expect(runner.errors.size).to eq(1)
expect(runner.errors[0].to_s).to eq(
"app/helpers/posts_helper.rb:2 - check 'update_attributes' return value or use 'update_attributes!'"
)
end
it 'allows update_attributes if return value is checked' do
content = <<-EOF
def my_method
@post.update_attributes(params) or raise "failed to save"
end
EOF
runner.review('app/helpers/posts_helper.rb', content)
expect(runner.errors.size).to eq(0)
end
it 'is not clever enough to allow update_attributes if value is returned from method' do
# This review is not clever enough to do a full liveness analysis
# of whether the returned value is used in all cases.
content = <<-EOF
class PostsController
def update
@post = Post.find params(:id)
if update_post
redirect_to view_post_path post
else
raise "post not saved"
end
end
def update_post
@post.update_attributes(params)
end
end
EOF
runner.review('app/controllers/posts_controller.rb', content)
expect(runner.errors.size).to eq(1)
expect(runner.errors[0].to_s).to eq(
"app/controllers/posts_controller.rb:12 - check 'update_attributes' return value or use 'update_attributes!'"
)
end
it 'warns you if you use create which is always unsafe' do
content = <<-EOF
class Post < ActiveRecord::Base
end
EOF
runner.prepare('app/models/post.rb', content)
content = <<-EOF
def my_method
if post = Post.create(params)
# post may or may not be saved here!
redirect_to view_post_path post
end
end
EOF
runner.review('app/helpers/posts_helper.rb', content)
expect(runner.errors.size).to eq(1)
expect(runner.errors[0].to_s).to eq(
"app/helpers/posts_helper.rb:2 - use 'create!' instead of 'create' as the latter may not always save"
)
end
it 'warns you if you use create with a block which is always unsafe' do
content = <<-EOF
module Blog
class Post < ActiveRecord::Base
end
end
EOF
runner.prepare('app/models/blog/post.rb', content)
content = <<-EOF
module Blog
class PostsHelper
def my_method
post = Post.create do |p|
p.title = 'new post'
end
if post
# post may or may not be saved here!
redirect_to view_post_path post
end
end
end
end
EOF
runner.review('app/helpers/blog/posts_helper.rb', content)
expect(runner.errors.size).to eq(1)
expect(runner.errors[0].to_s).to eq(
"app/helpers/blog/posts_helper.rb:4 - use 'create!' instead of 'create' as the latter may not always save"
)
end
it 'allows create called on non-model classes' do
content = <<-EOF
def my_method
pk12 = OpenSSL::PKCS12.create(
"", # password
descr, # friendly name
key,
cert)
end
EOF
runner.review('app/helpers/posts_helper.rb', content)
expect(runner.errors.map(&:to_s)).to eq([])
end
end
it 'does not check ignored files' do
runner = Core::Runner.new(reviews: described_class.new(ignored_files: /helpers/))
content = <<-EOF
def my_method
post = Posts.new do |p|
p.title = "foo"
end
post.save
end
EOF
runner.review('app/helpers/posts_helper.rb', content)
expect(runner.errors.size).to eq(0)
end
end
end
end
| ruby | MIT | 2ef40880d12ff8ed5f516871133ec569df03b192 | 2026-01-04T15:47:01.660067Z | false |
flyerhzm/rails_best_practices | https://github.com/flyerhzm/rails_best_practices/blob/2ef40880d12ff8ed5f516871133ec569df03b192/spec/rails_best_practices/reviews/default_scope_is_evil_review_spec.rb | spec/rails_best_practices/reviews/default_scope_is_evil_review_spec.rb | # frozen_string_literal: true
require 'spec_helper'
module RailsBestPractices
module Reviews
describe DefaultScopeIsEvilReview do
let(:runner) { Core::Runner.new(reviews: described_class.new) }
it 'detects default_scope with -> syntax' do
content = <<-EOF
class User < ActiveRecord::Base
default_scope -> { order('created_at desc') }
end
EOF
runner.review('app/models/user.rb', content)
expect(runner.errors.size).to eq(1)
expect(runner.errors[0].to_s).to eq('app/models/user.rb:2 - default_scope is evil')
end
it 'detects default_scope with old syntax' do
content = <<-EOF
class User < ActiveRecord::Base
default_scope order('created_at desc')
end
EOF
runner.review('app/models/user.rb', content)
expect(runner.errors.size).to eq(1)
expect(runner.errors[0].to_s).to eq('app/models/user.rb:2 - default_scope is evil')
end
it 'does not detect default_scope' do
content = <<-EOF
class User < ActiveRecord::Base
scope :default, -> { order('created_at desc') }
end
EOF
runner.review('app/models/user.rb', content)
expect(runner.errors.size).to eq(0)
end
it 'does not check ignored files' do
runner = Core::Runner.new(reviews: described_class.new(ignored_files: /user/))
content = <<-EOF
class User < ActiveRecord::Base
default_scope -> { order('created_at desc') }
end
EOF
runner.review('app/models/user.rb', content)
expect(runner.errors.size).to eq(0)
end
end
end
end
| ruby | MIT | 2ef40880d12ff8ed5f516871133ec569df03b192 | 2026-01-04T15:47:01.660067Z | false |
flyerhzm/rails_best_practices | https://github.com/flyerhzm/rails_best_practices/blob/2ef40880d12ff8ed5f516871133ec569df03b192/spec/rails_best_practices/reviews/add_model_virtual_attribute_review_spec.rb | spec/rails_best_practices/reviews/add_model_virtual_attribute_review_spec.rb | # frozen_string_literal: true
require 'spec_helper'
module RailsBestPractices
module Reviews
describe AddModelVirtualAttributeReview do
let(:runner) { Core::Runner.new(reviews: described_class.new) }
it 'adds model virtual attribute' do
content = <<-EOF
class UsersController < ApplicationController
def create
@user = User.new(params[:user])
@user.first_name = params[:full_name].split(' ', 2).first
@user.last_name = params[:full_name].split(' ', 2).last
@user.save
end
end
EOF
runner.review('app/controllers/users_controller.rb', content)
expect(runner.errors.size).to eq(1)
expect(runner.errors[0].to_s).to eq(
'app/controllers/users_controller.rb:2 - add model virtual attribute (for @user)'
)
end
it 'adds model virtual attribute with local assignment' do
content = <<-EOF
class UsersController < ApplicationController
def create
user = User.new(params[:user])
user.first_name = params[:full_name].split(' ', 2).first
user.last_name = params[:full_name].split(' ', 2).last
user.save
end
end
EOF
runner.review('app/controllers/users_controller.rb', content)
expect(runner.errors.size).to eq(1)
expect(runner.errors[0].to_s).to eq(
'app/controllers/users_controller.rb:2 - add model virtual attribute (for user)'
)
end
it 'does not add model virtual attribute with differen param' do
content = <<-EOF
class UsersController < ApplicationController
def create
@user = User.new(params[:user])
@user.first_name = params[:first_name]
@user.last_name = params[:last_name]
@user.save
end
end
EOF
runner.review('app/controllers/users_controller.rb', content)
expect(runner.errors.size).to eq(0)
end
it 'does not add model virtual attribute with read' do
content = <<-EOF
class UsersController < ApplicationController
def show
if params[:id]
@user = User.find(params[:id])
else
@user = current_user
end
end
end
EOF
runner.review('app/controllers/users_controller.rb', content)
expect(runner.errors.size).to eq(0)
end
it 'adds model virtual attribute with two dimension params' do
content = <<-EOF
class UsersController < ApplicationController
def create
@user = User.new(params[:user])
@user.first_name = params[:user][:full_name].split(' ', 2).first
@user.last_name = params[:user][:full_name].split(' ', 2).last
@user.save
end
end
EOF
runner.review('app/controllers/users_controller.rb', content)
expect(runner.errors.size).to eq(1)
expect(runner.errors[0].to_s).to eq(
'app/controllers/users_controller.rb:2 - add model virtual attribute (for @user)'
)
end
it 'noes add model virtual attribute with two dimension params' do
content = <<-EOF
class UsersController < ApplicationController
def create
@user = User.new(params[:user])
@user.first_name = params[:user][:first_name]
@user.last_name = params[:user][:last_name]
@user.save
end
end
EOF
runner.review('app/controllers/users_controller.rb', content)
expect(runner.errors.size).to eq(0)
end
it 'does not check ignored files' do
runner = Core::Runner.new(reviews: described_class.new(ignored_files: /user/))
content = <<-EOF
class UsersController < ApplicationController
def create
@user = User.new(params[:user])
@user.first_name = params[:full_name].split(' ', 2).first
@user.last_name = params[:full_name].split(' ', 2).last
@user.save
end
end
EOF
runner.review('app/controllers/users_controller.rb', content)
expect(runner.errors.size).to eq(0)
end
end
end
end
| ruby | MIT | 2ef40880d12ff8ed5f516871133ec569df03b192 | 2026-01-04T15:47:01.660067Z | false |
flyerhzm/rails_best_practices | https://github.com/flyerhzm/rails_best_practices/blob/2ef40880d12ff8ed5f516871133ec569df03b192/spec/rails_best_practices/reviews/not_use_default_route_review_spec.rb | spec/rails_best_practices/reviews/not_use_default_route_review_spec.rb | # frozen_string_literal: true
require 'spec_helper'
module RailsBestPractices
module Reviews
describe NotUseDefaultRouteReview do
let(:runner) { Core::Runner.new(reviews: described_class.new) }
it 'does not use default route' do
content = <<-EOF
RailsBestpracticesCom::Application.routes.draw do |map|
resources :posts
match ':controller(/:action(/:id(.:format)))'
end
EOF
runner.review('config/routes.rb', content)
expect(runner.errors.size).to eq(1)
expect(runner.errors[0].to_s).to eq('config/routes.rb:4 - not use default route')
end
it 'noes not use default route' do
content = <<-EOF
RailsBestpracticesCom::Application.routes.draw do |map|
resources :posts
end
EOF
runner.review('config/routes.rb', content)
expect(runner.errors.size).to eq(0)
end
it 'does not check ignored files' do
runner = Core::Runner.new(reviews: described_class.new(ignored_files: %r{config/routes\.rb}))
content = <<-EOF
RailsBestpracticesCom::Application.routes.draw do |map|
resources :posts
match ':controller(/:action(/:id(.:format)))'
end
EOF
runner.review('config/routes.rb', content)
expect(runner.errors.size).to eq(0)
end
end
end
end
| ruby | MIT | 2ef40880d12ff8ed5f516871133ec569df03b192 | 2026-01-04T15:47:01.660067Z | false |
flyerhzm/rails_best_practices | https://github.com/flyerhzm/rails_best_practices/blob/2ef40880d12ff8ed5f516871133ec569df03b192/spec/rails_best_practices/reviews/remove_unused_methods_in_models_review_spec.rb | spec/rails_best_practices/reviews/remove_unused_methods_in_models_review_spec.rb | # frozen_string_literal: true
require 'spec_helper'
module RailsBestPractices
module Reviews
describe RemoveUnusedMethodsInModelsReview do
let(:runner) do
Core::Runner.new(
prepares: Prepares::ModelPrepare.new, reviews: described_class.new('except_methods' => ['*#set_cache'])
)
end
context 'private' do
it 'removes unused methods' do
content = <<-EOF
class Post < ActiveRecord::Base
def find; end
private
def find_by_sql; end
end
EOF
runner.prepare('app/models/post.rb', content)
runner.review('app/models/post.rb', content)
content = <<-EOF
class PostsController < ApplicationController
def get
Post.new.find
end
end
EOF
runner.review('app/controllers/posts_controller.rb', content)
runner.after_review
expect(runner.errors.size).to eq(1)
expect(runner.errors[0].to_s).to eq('app/models/post.rb:4 - remove unused methods (Post#find_by_sql)')
end
it 'does not remove unused methods with except_methods' do
content = <<-EOF
class Post < ActiveRecord::Base
def set_cache; end
end
EOF
runner.prepare('app/models/post.rb', content)
runner.review('app/models/post.rb', content)
runner.after_review
expect(runner.errors.size).to eq(0)
end
it 'does not remove unused methods with var_ref' do
content = <<-EOF
class Post < ActiveRecord::Base
def find
find_by_sql
end
private
def find_by_sql; end
end
EOF
runner.prepare('app/models/post.rb', content)
runner.review('app/models/post.rb', content)
content = <<-EOF
class PostsController < ApplicationController
def get
Post.new.find
end
end
EOF
runner.review('app/controllers/posts_controller.rb', content)
runner.after_review
expect(runner.errors.size).to eq(0)
end
it 'does not remove unused methods with callback' do
content = <<-EOF
class Post < ActiveRecord::Base
after_save :expire_cache
private
def expire_cache; end
end
EOF
runner.prepare('app/models/post.rb', content)
runner.review('app/models/post.rb', content)
runner.after_review
expect(runner.errors.size).to eq(0)
end
it 'does not remove unused method with command' do
content = <<-EOF
class Post < ActiveRecord::Base
def fetch
get(position: 'first')
end
private
def get(options={}); end
end
EOF
runner.prepare('app/models/post.rb', content)
runner.review('app/models/post.rb', content)
content = <<-EOF
class PostsController < ApplicationController
def get
Post.new.fetch
end
end
EOF
runner.review('app/controllers/posts_controller.rb', content)
runner.after_review
expect(runner.errors.size).to eq(0)
end
it 'does not remove unused method with call' do
content = <<-EOF
class Post < ActiveRecord::Base
def conditions
self.build_conditions({})
end
private
def build_conditions(conditions={}); end
end
EOF
runner.prepare('app/models/post.rb', content)
runner.review('app/models/post.rb', content)
content = <<-EOF
class PostsController < ApplicationController
def get
Post.new.conditions
end
end
EOF
runner.review('app/controllers/posts_controller.rb', content)
runner.after_review
expect(runner.errors.size).to eq(0)
end
it 'does not remove unused method with message' do
content = <<-EOF
class Post < ActiveRecord::Base
def save
transaction true do
self.update
end
end
private
def transaction(force); end
end
EOF
runner.prepare('app/models/post.rb', content)
runner.review('app/models/post.rb', content)
content = <<-EOF
class PostsController < ApplicationController
def create
Post.new.save
end
end
EOF
runner.review('app/controllers/posts_controller.rb', content)
runner.after_review
expect(runner.errors.size).to eq(0)
end
it 'does not remove unused method with validation condition' do
content = <<-EOF
class Post < ActiveRecord::Base
validates_uniqueness_of :login, if: :email_blank?
private
def email_blank?; end
end
EOF
runner.prepare('app/models/post.rb', content)
runner.review('app/models/post.rb', content)
runner.after_review
expect(runner.errors.size).to eq(0)
end
it 'does not remove unused method with aasm' do
content = <<-EOF
class Post < ActiveRecord::Base
aasm_state :accepted, enter: [:update_datetime]
private
def update_datetime; end
end
EOF
runner.prepare('app/models/post.rb', content)
runner.review('app/models/post.rb', content)
runner.after_review
expect(runner.errors.size).to eq(0)
end
it 'does not remove unused method with initialize' do
content = <<-EOF
class Post < ActiveRecord::Base
private
def initialize; end
end
EOF
runner.prepare('app/models/post.rb', content)
runner.review('app/models/post.rb', content)
runner.after_review
expect(runner.errors.size).to eq(0)
end
end
context 'public' do
it 'removes unused methods' do
content = <<-EOF
class Post < ActiveRecord::Base
def fetch; end
end
EOF
runner.prepare('app/models/post.rb', content)
runner.after_review
expect(runner.errors.size).to eq(1)
expect(runner.errors[0].to_s).to eq('app/models/post.rb:2 - remove unused methods (Post#fetch)')
end
it 'does not remove unused methods' do
content = <<-EOF
class Post < ActiveRecord::Base
def fetch; end
end
EOF
runner.prepare('app/models/post.rb', content)
content = <<-EOF
class PostsController < ApplicationController
def show
@post.fetch
end
end
EOF
runner.review('app/controllers/posts_controller.rb', content)
runner.after_review
expect(runner.errors.size).to eq(0)
end
it 'does not remove unused methods for attribute assignment' do
content = <<-EOF
class Post < ActiveRecord::Base
def user=(user); end
end
EOF
runner.prepare('app/models/post.rb', content)
runner.review('app/models/post.rb', content)
runner.after_review
expect(runner.errors.size).to eq(0)
end
it 'does not remove unused methods for try' do
content = <<-EOF
class Post < ActiveRecord::Base
def find(user_id); end
end
EOF
runner.prepare('app/models/post.rb', content)
runner.review('app/models/post.rb', content)
content = <<-EOF
class PostsController < ApplicationController
def find
Post.new.try(:find, current_user.id)
end
end
EOF
runner.review('app/controllers/posts_controller.rb', content)
runner.after_review
expect(runner.errors.size).to eq(0)
end
it 'does not remove unused methods for send' do
content = <<-EOF
class Post < ActiveRecord::Base
def find(user_id); end
end
EOF
runner.prepare('app/models/post.rb', content)
runner.review('app/models/post.rb', content)
content = <<-EOF
class PostsController < ApplicationController
def find
Post.new.send(:find, current_user.id)
end
end
EOF
runner.review('app/controllers/posts_controller.rb', content)
runner.after_review
expect(runner.errors.size).to eq(0)
end
it 'removes unused methods for send string_embexpre' do
content = <<-EOF
class Post < ActiveRecord::Base
def find_first; end
end
EOF
runner.prepare('app/models/post.rb', content)
runner.review('app/models/post.rb', content)
content = <<-EOF
class PostsController < ApplicationController
def find
type = "first"
Post.new.send("find_\#{type}")
end
end
EOF
runner.review('app/controllers/posts_controller.rb', content)
runner.after_review
expect(runner.errors.size).to eq(1)
end
it 'removes unused methods for send variable' do
content = <<-EOF
class Post < ActiveRecord::Base
def first; end
end
EOF
runner.prepare('app/models/post.rb', content)
runner.review('app/models/post.rb', content)
content = <<-EOF
class PostsController < ApplicationController
def find
type = "first"
Post.new.send(type)
end
end
EOF
runner.review('app/controllers/posts_controller.rb', content)
runner.after_review
expect(runner.errors.size).to eq(1)
end
end
context 'protected' do
it 'does not remove unused methods' do
content = <<-EOF
class Post < ActiveRecord::Base
protected
def test; end
end
EOF
runner.prepare('app/models/post.rb', content)
runner.review('app/models/post.rb', content)
content = <<-EOF
class PostsController < ApplicationController
def test
Post.new.test
end
end
EOF
runner.review('app/controllers/posts_controller.rb', content)
runner.after_review
expect(runner.errors.size).to eq(1)
expect(runner.errors[0].to_s).to eq('app/models/post.rb:3 - remove unused methods (Post#test)')
end
it 'does not remove unused methods' do
post_content = <<-EOF
class Post < ActiveRecord::Base
protected
def test; end
end
EOF
blog_post_content = <<-EOF
class BlogPost < Post
def play
test
end
end
EOF
runner.prepare('app/models/post.rb', post_content)
runner.prepare('app/models/blog_post.rb', blog_post_content)
runner.review('app/models/post.rb', post_content)
runner.review('app/models/blog_post.rb', blog_post_content)
content = <<-EOF
class BlogPostsController < ApplicationController
def play
BlogPost.new.play
end
end
EOF
runner.review('app/controllers/posts_controller.rb', content)
runner.after_review
expect(runner.errors.size).to eq(0)
end
end
context 'named_scope' do
it 'does not remove unused named_scope' do
content = <<-EOF
class Post < ActiveRecord::Base
named_scope :active, conditions: {active: true}
end
EOF
runner.prepare('app/models/post.rb', content)
runner.review('app/models/post.rb', content)
content = <<-EOF
class PostsController < ApplicationController
def index
@posts = Post.active
end
end
EOF
runner.review('app/controllers/posts_controller.rb', content)
runner.after_review
expect(runner.errors.size).to eq(0)
end
it 'removes unused named_scope' do
content = <<-EOF
class Post < ActiveRecord::Base
named_scope :active, conditions: {active: true}
end
EOF
runner.prepare('app/models/post.rb', content)
runner.review('app/models/post.rb', content)
runner.after_review
expect(runner.errors.size).to eq(1)
expect(runner.errors[0].to_s).to eq('app/models/post.rb:2 - remove unused methods (Post#active)')
end
end
context 'scope' do
it 'does not remove unused scope' do
content = <<-EOF
class Post < ActiveRecord::Base
scope :active, where(active: true)
end
EOF
runner.prepare('app/models/post.rb', content)
runner.review('app/models/post.rb', content)
content = <<-EOF
class PostsController < ApplicationController
def index
@posts = Post.active
end
end
EOF
runner.review('app/controllers/posts_controller.rb', content)
runner.after_review
expect(runner.errors.size).to eq(0)
end
it 'removes unused named_scope' do
content = <<-EOF
class Post < ActiveRecord::Base
scope :active, where(active: true)
end
EOF
runner.prepare('app/models/post.rb', content)
runner.review('app/models/post.rb', content)
runner.after_review
expect(runner.errors.size).to eq(1)
expect(runner.errors[0].to_s).to eq('app/models/post.rb:2 - remove unused methods (Post#active)')
end
end
context 'alias' do
it 'does not remove unused method with alias' do
content = <<-EOF
class Post < ActiveRecord::Base
def old; end
alias new old
end
EOF
runner.prepare('app/models/post.rb', content)
runner.review('app/models/post.rb', content)
content = <<-EOF
class PostsController < ApplicationController
def show
@post.new
end
end
EOF
runner.review('app/controllers/posts_controller.rb', content)
runner.after_review
expect(runner.errors.size).to eq(0)
end
it 'does not remove unused method with symbol alias' do
content = <<-EOF
class Post < ActiveRecord::Base
def old; end
alias :new :old
end
EOF
runner.prepare('app/models/post.rb', content)
runner.review('app/models/post.rb', content)
content = <<-EOF
class PostsController < ApplicationController
def show
@post.new
end
end
EOF
runner.review('app/controllers/posts_controller.rb', content)
runner.after_review
expect(runner.errors.size).to eq(0)
end
it 'does not remove unused method with alias_method' do
content = <<-EOF
class Post < ActiveRecord::Base
def old; end
alias_method :new, :old
end
EOF
runner.prepare('app/models/post.rb', content)
runner.review('app/models/post.rb', content)
content = <<-EOF
class PostsController < ApplicationController
def show
@post.new
end
end
EOF
runner.review('app/controllers/posts_controller.rb', content)
runner.after_review
expect(runner.errors.size).to eq(0)
end
it 'does not remove unused method with alias_method_chain' do
content = <<-EOF
class Post < ActiveRecord::Base
def method_with_feature; end
alias_method_chain :method, :feature
end
EOF
runner.prepare('app/models/post.rb', content)
runner.review('app/models/post.rb', content)
content = <<-EOF
class PostsController < ApplicationController
def show
@post.method
end
end
EOF
runner.review('app/controllers/posts_controller.rb', content)
runner.after_review
expect(runner.errors.size).to eq(0)
end
end
context 'methods hash' do
it 'does not remove unused method with methods hash' do
content = <<-EOF
class Post < ActiveRecord::Base
def to_xml(options = {})
super options.merge(exclude: :visible, methods: [:is_discussion_conversation])
end
def is_discussion_conversation; end
end
EOF
runner.prepare('app/models/post.rb', content)
runner.review('app/models/post.rb', content)
runner.after_review
expect(runner.errors.size).to eq(0)
end
end
if RUBY_VERSION.to_f > 3.0
context 'short syntax value' do
it 'does not remove unused method' do
content = <<-EOF
class Post < ActiveRecord::Base
def build
new(value:)
end
def value
'value'
end
end
EOF
runner.prepare('app/models/post.rb', content)
runner.review('app/models/post.rb', content)
runner.after_review
expect(runner.errors.size).to eq(1)
end
end
end
context 'callbacks' do
it 'does not remove unused method' do
content = <<-EOF
class Post < ActiveRecord::Base
before_save :init_columns
after_destroy :remove_dependencies
protected
def init_columns; end
def remove_dependencies; end
end
EOF
runner.prepare('app/models/post.rb', content)
runner.review('app/models/post.rb', content)
runner.after_review
expect(runner.errors.size).to eq(0)
end
end
context 'validates' do
it 'does not remove unused method' do
content = <<-EOF
class Post < ActiveRecord::Base
validate :valid_birth_date
protected
def valid_birth_date; end
end
EOF
runner.prepare('app/models/post.rb', content)
runner.review('app/models/post.rb', content)
runner.after_review
expect(runner.errors.size).to eq(0)
end
it 'does not remove unused method for validate_on_create and validate_on_update' do
content = <<-EOF
class Post < ActiveRecord::Base
validate_on_create :valid_email
validate_on_update :valid_birth_date
protected
def valid_email; end
def valid_birth_date; end
end
EOF
runner.prepare('app/models/post.rb', content)
runner.review('app/models/post.rb', content)
runner.after_review
expect(runner.errors.size).to eq(0)
end
it 'does not remove unused methods for to_param' do
content = <<-EOF
class Post < ActiveRecord::Base
def to_param
id
end
end
EOF
runner.prepare('app/models/post.rb', content)
runner.review('app/models/post.rb', content)
runner.after_review
expect(runner.errors.size).to eq(0)
end
end
context 'helper method' do
it 'does not remove unused method for coommand_call collection_select' do
content = <<-EOF
class Category < ActiveRecord::Base
def indented_name; end
end
EOF
runner.prepare('app/models/category.rb', content)
runner.review('app/models/category.rb', content)
content = <<-EOF
<%= f.collection_select :parent_id, Category.all_hierarchic(except: @category), :id, :indented_name, {include_blank: true} %>
EOF
runner.review('app/views/categories/_form.html.erb', content)
runner.after_review
expect(runner.errors.size).to eq(0)
end
it 'does not remove unused method for command collection_select' do
content = <<-EOF
class Category < ActiveRecord::Base
def indented_name; end
end
EOF
runner.prepare('app/models/category.rb', content)
runner.review('app/models/category.rb', content)
content = <<-EOF
<%= collection_select :category, :parent_id, Category.all_hierarchic(except: @category), :id, :indented_name, {include_blank: true} %>
EOF
runner.review('app/views/categories/_form.html.erb', content)
runner.after_review
expect(runner.errors.size).to eq(0)
end
it 'does not remove unused method for options_from_collection_for_select' do
content = <<-EOF
class Category < ActiveRecord::Base
def indented_name; end
end
EOF
runner.prepare('app/models/category.rb', content)
runner.review('app/models/category.rb', content)
content = <<-EOF
<%= select_tag 'category', options_from_collection_for_select(Category.all_hierachic(except: @category), :id, :indented_name) %>
EOF
runner.review('app/views/categories/_form.html.erb', content)
runner.after_review
expect(runner.errors.size).to eq(0)
end
end
it 'does not remove unused methods for rabl view' do
content = <<-EOF
class User
def first_name; end
def last_name; end
end
EOF
runner.prepare('app/models/user.rb', content)
runner.review('app/models/user.rb', content)
content = <<-EOF
node :full_name do |u|
u.first_name + " " + u.last_name
end
EOF
runner.review('app/views/users/show.json.rabl', content)
runner.after_review
expect(runner.errors.size).to eq(0)
end
it 'does not skip :call as call message' do
content = <<-EOF
module DateRange
RANGES = lambda {
last_month = {
'range' => lambda { [date_from_time.(31.days.ago), date_from_time.(Time.now)] },
'value' => 'last_month',
'label' => 'Last month'}
}[]
end
EOF
runner.prepare('app/mixins/date_range.rb', content)
runner.review('app/mixins/date_range.rb', content)
end
it 'does not check ignored files' do
runner =
Core::Runner.new(
prepares: Prepares::ModelPrepare.new,
reviews: described_class.new(except_methods: [], ignored_files: /post/)
)
content = <<-EOF
class Post < ActiveRecord::Base
def find; end
private
def find_by_sql; end
end
EOF
runner.prepare('app/models/post.rb', content)
runner.review('app/models/post.rb', content)
content = <<-EOF
class PostsController < ApplicationController
def get
Post.new.find
end
end
EOF
runner.review('app/controllers/posts_controller.rb', content)
runner.after_review
expect(runner.errors.size).to eq(0)
end
end
end
end
| ruby | MIT | 2ef40880d12ff8ed5f516871133ec569df03b192 | 2026-01-04T15:47:01.660067Z | false |
flyerhzm/rails_best_practices | https://github.com/flyerhzm/rails_best_practices/blob/2ef40880d12ff8ed5f516871133ec569df03b192/spec/rails_best_practices/reviews/remove_empty_helpers_review_spec.rb | spec/rails_best_practices/reviews/remove_empty_helpers_review_spec.rb | # frozen_string_literal: true
require 'spec_helper'
module RailsBestPractices
module Reviews
describe RemoveEmptyHelpersReview do
let(:runner) { Core::Runner.new(reviews: described_class.new) }
it 'removes empty helpers' do
content = <<-EOF
module PostsHelper
end
EOF
runner.review('app/helpers/posts_helper.rb', content)
expect(runner.errors.size).to eq(1)
expect(runner.errors[0].to_s).to eq('app/helpers/posts_helper.rb:1 - remove empty helpers')
end
it 'does not remove empty helpers' do
content = <<-EOF
module PostsHelper
def post_link(post)
post_path(post)
end
end
EOF
runner.review('app/helpers/posts_helper.rb', content)
expect(runner.errors.size).to eq(0)
end
it 'does not remove empty application_helper' do
content = <<-EOF
module ApplicationHelper
end
EOF
runner.review('app/helpers/application_helper.rb', content)
expect(runner.errors.size).to eq(0)
end
it 'does not check ignored files' do
runner = Core::Runner.new(reviews: described_class.new(ignored_files: /posts_helper/))
content = <<-EOF
module PostsHelper
end
EOF
runner.review('app/helpers/posts_helper.rb', content)
expect(runner.errors.size).to eq(0)
end
end
end
end
| ruby | MIT | 2ef40880d12ff8ed5f516871133ec569df03b192 | 2026-01-04T15:47:01.660067Z | false |
flyerhzm/rails_best_practices | https://github.com/flyerhzm/rails_best_practices/blob/2ef40880d12ff8ed5f516871133ec569df03b192/spec/rails_best_practices/reviews/replace_complex_creation_with_factory_method_review_spec.rb | spec/rails_best_practices/reviews/replace_complex_creation_with_factory_method_review_spec.rb | # frozen_string_literal: true
require 'spec_helper'
module RailsBestPractices
module Reviews
describe ReplaceComplexCreationWithFactoryMethodReview do
let(:runner) { Core::Runner.new(reviews: described_class.new) }
it 'replaces complex creation with factory method' do
content = <<-EOF
class InvoiceController < ApplicationController
def create
@invoice = Invoice.new(params[:invoice])
@invoice.address = current_user.address
@invoice.phone = current_user.phone
@invoice.vip = (@invoice.amount > 1000)
if Time.now.day > 15
@invoice.deliver_time = Time.now + 2.month
else
@invoice.deliver_time = Time.now + 1.month
end
@invoice.save
end
end
EOF
runner.review('app/controllers/invoices_controller.rb', content)
expect(runner.errors.size).to eq(1)
expect(runner.errors[0].to_s).to eq(
'app/controllers/invoices_controller.rb:2 - replace complex creation with factory method (@invoice attribute_assignment_count > 2)'
)
end
it 'does not replace complex creation with factory method with simple creation' do
content = <<-EOF
class InvoiceController < ApplicationController
def create
@invoice = Invoice.new(params[:invoice])
@invoice.address = current_user.address
@invoice.phone = current_user.phone
@invoice.save
end
end
EOF
runner.review('app/controllers/invoices_controller.rb', content)
expect(runner.errors.size).to eq(0)
end
it 'does not replace complex creation with factory method when attrasgn_count is 5' do
content = <<-EOF
class InvoiceController < ApplicationController
def create
@invoice = Invoice.new(params[:invoice])
@invoice.address = current_user.address
@invoice.phone = current_user.phone
@invoice.vip = (@invoice.amount > 1000)
if Time.now.day > 15
@invoice.deliver_time = Time.now + 2.month
else
@invoice.deliver_time = Time.now + 1.month
end
@invoice.save
end
end
EOF
runner = Core::Runner.new(reviews: described_class.new('attribute_assignment_count' => 5))
runner.review('app/controllers/invoices_controller.rb', content)
expect(runner.errors.size).to eq(0)
end
it 'does not check ignored files' do
runner = Core::Runner.new(reviews: described_class.new(ignored_files: /invoices_controller/))
content = <<-EOF
class InvoiceController < ApplicationController
def create
@invoice = Invoice.new(params[:invoice])
@invoice.address = current_user.address
@invoice.phone = current_user.phone
@invoice.vip = (@invoice.amount > 1000)
if Time.now.day > 15
@invoice.deliver_time = Time.now + 2.month
else
@invoice.deliver_time = Time.now + 1.month
end
@invoice.save
end
end
EOF
runner.review('app/controllers/invoices_controller.rb', content)
expect(runner.errors.size).to eq(0)
end
end
end
end
| ruby | MIT | 2ef40880d12ff8ed5f516871133ec569df03b192 | 2026-01-04T15:47:01.660067Z | false |
flyerhzm/rails_best_practices | https://github.com/flyerhzm/rails_best_practices/blob/2ef40880d12ff8ed5f516871133ec569df03b192/spec/rails_best_practices/reviews/isolate_seed_data_review_spec.rb | spec/rails_best_practices/reviews/isolate_seed_data_review_spec.rb | # frozen_string_literal: true
require 'spec_helper'
module RailsBestPractices
module Reviews
describe IsolateSeedDataReview do
let(:runner) { Core::Runner.new(reviews: described_class.new) }
context 'create' do
it 'isolates seed data' do
content = <<-EOF
class CreateRoles < ActiveRecord::Migration
def self.up
create_table "roles", force: true do |t|
t.string :name
end
["admin", "author", "editor", "account"].each do |name|
Role.create!(name: name)
end
end
def self.down
drop_table "roles"
end
end
EOF
runner.review('db/migrate/20090818130258_create_roles.rb', content)
expect(runner.errors.size).to eq(1)
expect(runner.errors[0].to_s).to eq('db/migrate/20090818130258_create_roles.rb:8 - isolate seed data')
end
end
context 'new and save' do
it 'isolates seed data for local variable' do
content = <<-EOF
class CreateRoles < ActiveRecord::Migration
def self.up
create_table "roles", force: true do |t|
t.string :name
end
["admin", "author", "editor", "account"].each do |name|
role = Role.new(name: name)
role.save!
end
end
def self.down
drop_table "roles"
end
end
EOF
runner.review('db/migrate/20090818130258_create_roles.rb', content)
expect(runner.errors.size).to eq(1)
expect(runner.errors[0].to_s).to eq('db/migrate/20090818130258_create_roles.rb:9 - isolate seed data')
end
it 'isolates seed data for instance variable' do
content = <<-EOF
class CreateRoles < ActiveRecord::Migration
def self.up
create_table "roles", force: true do |t|
t.string :name
end
["admin", "author", "editor", "account"].each do |name|
@role = Role.new(name: name)
@role.save!
end
end
def self.down
drop_table "roles"
end
end
EOF
runner.review('db/migrate/20090818130258_create_roles.rb', content)
expect(runner.errors.size).to eq(1)
expect(runner.errors[0].to_s).to eq('db/migrate/20090818130258_create_roles.rb:9 - isolate seed data')
end
end
it 'does not isolate seed data without data insert' do
content = <<-EOF
class CreateRoles < ActiveRecord::Migration
def self.up
create_table "roles", force: true do |t|
t.string :name
end
end
def self.down
drop_table "roles"
end
end
EOF
runner.review('db/migrate/20090818130258_create_roles.rb', content)
expect(runner.errors.size).to eq(0)
end
it 'does not check ignored files' do
runner = Core::Runner.new(reviews: described_class.new(ignored_files: /create_roles/))
content = <<-EOF
class CreateRoles < ActiveRecord::Migration
def self.up
create_table "roles", force: true do |t|
t.string :name
end
["admin", "author", "editor", "account"].each do |name|
Role.create!(name: name)
end
end
def self.down
drop_table "roles"
end
end
EOF
runner.review('db/migrate/20090818130258_create_roles.rb', content)
expect(runner.errors.size).to eq(0)
end
end
end
end
| ruby | MIT | 2ef40880d12ff8ed5f516871133ec569df03b192 | 2026-01-04T15:47:01.660067Z | false |
flyerhzm/rails_best_practices | https://github.com/flyerhzm/rails_best_practices/blob/2ef40880d12ff8ed5f516871133ec569df03b192/spec/rails_best_practices/reviews/remove_unused_methods_in_controllers_review_spec.rb | spec/rails_best_practices/reviews/remove_unused_methods_in_controllers_review_spec.rb | # frozen_string_literal: true
require 'spec_helper'
module RailsBestPractices
module Reviews
describe RemoveUnusedMethodsInControllersReview do
let(:runner) do
Core::Runner.new(
prepares: [Prepares::ControllerPrepare.new, Prepares::RoutePrepare.new],
reviews: described_class.new('except_methods' => ['ExceptableController#*'])
)
end
context 'private/protected' do
it 'removes unused methods' do
content = <<-EOF
RailsBestPracticesCom::Application.routes.draw do
resources :posts do
member do
post 'link_to/:other_id' => 'posts#link_to_post'
post 'extra_update' => 'posts#extra_update'
end
end
end
EOF
runner.prepare('config/routes.rb', content)
content = <<-EOF
class PostsController < ActiveRecord::Base
def show; end
def extra_update; end
def link_to_post; end
protected
def load_post; end
private
def load_user; end
end
EOF
runner.prepare('app/controllers/posts_controller.rb', content)
runner.review('app/controllers/posts_controller.rb', content)
runner.after_review
expect(runner.errors.size).to eq(2)
expect(runner.errors[0].to_s).to eq(
'app/controllers/posts_controller.rb:6 - remove unused methods (PostsController#load_post)'
)
expect(runner.errors[1].to_s).to eq(
'app/controllers/posts_controller.rb:8 - remove unused methods (PostsController#load_user)'
)
end
it 'does not remove unused methods for before_filter' do
content = <<-EOF
RailsBestPracticesCom::Application.routes.draw do
resources :posts
end
EOF
runner.prepare('config/routes.rb', content)
content = <<-EOF
class PostsController < ActiveRecord::Base
before_filter :load_post, :load_user
def show; end
protected
def load_post; end
def load_user; end
end
EOF
runner.prepare('app/controllers/posts_controller.rb', content)
runner.review('app/controllers/posts_controller.rb', content)
runner.after_review
expect(runner.errors.size).to eq(0)
end
it 'does not remove unused methods for around_filter' do
content = <<-EOF
RailsBestPracticesCom::Application.routes.draw do
resources :posts
end
EOF
runner.prepare('config/routes.rb', content)
content = <<-EOF
class PostsController < ActiveRecord::Base
around_filter :set_timestamp
protected
def set_timestamp
Time.zone = "Pacific Time (US & Canada)"
yield
ensure
Time.zone = "UTC"
end
end
EOF
runner.prepare('app/controllers/posts_controller.rb', content)
runner.review('app/controllers/posts_controller.rb', content)
runner.after_review
expect(runner.errors.size).to eq(0)
end
it 'does not remove unused methods for around_action (new syntax)' do
content = <<-EOF
class PostsController < ActiveRecord::Base
around_action :use_time_zone
protected
def use_time_zone(&block)
Time.use_zone(current_user.time_zone, &block)
end
end
EOF
runner.prepare('app/controllers/posts_controller.rb', content)
runner.review('app/controllers/posts_controller.rb', content)
runner.after_review
expect(runner.errors.size).to eq(0)
end
it 'does not remove unused methods for layout' do
content = <<-EOF
RailsBestPracticesCom::Application.routes.draw do
resources :posts
end
EOF
runner.prepare('config/routes.rb', content)
content = <<-EOF
class PostsController < ActiveRecord::Base
layout :choose_layout
private
def choose_layout
"default"
end
end
EOF
runner.prepare('app/controllers/posts_controller.rb', content)
runner.review('app/controllers/posts_controller.rb', content)
runner.after_review
expect(runner.errors.size).to eq(0)
end
it 'does not remove inherited_resources methods' do
content = <<-EOF
RailsBestPracticesCom::Application.routes.draw do
resources :posts
end
EOF
runner.prepare('config/routes.rb', content)
content = <<-EOF
class PostsController < InheritedResources::Base
def show; end
protected
def resource; end
def collection; end
def begin_of_association_chain; end
end
EOF
runner.prepare('app/controllers/posts_controller.rb', content)
runner.review('app/controllers/posts_controller.rb', content)
runner.after_review
expect(runner.errors.size).to eq(0)
end
end
context 'public' do
it 'removes unused methods' do
content = <<-EOF
RailsBestPracticesCom::Application.routes.draw do
resources :posts
end
EOF
runner.prepare('config/routes.rb', content)
content = <<-EOF
class PostsController < ApplicationController
def show; end
def list; end
end
EOF
runner.prepare('app/controllers/posts_controller.rb', content)
runner.review('app/controllers/posts_controller.rb', content)
runner.after_review
expect(runner.errors.size).to eq(1)
expect(runner.errors[0].to_s).to eq(
'app/controllers/posts_controller.rb:3 - remove unused methods (PostsController#list)'
)
end
it 'does not remove inline routes' do
content = <<-EOF
RailsBestPracticesCom::Application.routes.draw do
resources :posts, only: :none do
get :display, :list, on: :member
end
end
EOF
runner.prepare('config/routes.rb', content)
content = <<-EOF
class PostsController < ApplicationController
def display; end
def list; end
end
EOF
runner.prepare('app/controllers/posts_controller.rb', content)
runner.review('app/controllers/posts_controller.rb', content)
runner.after_review
expect(runner.errors.size).to eq(0)
end
it 'does not remove unused methods if all actions are used in route' do
content = <<-EOF
ActionController::Routing::Routes.draw do |map|
map.connect 'internal/:action/*whatever', controller: "internal"
end
EOF
runner.prepare('config/routes.rb', content)
content = <<-EOF
class InternalController < ApplicationController
def list; end
def delete; end
def whatever; end
end
EOF
runner.prepare('app/controllers/internal_controller.rb', content)
runner.review('app/controllers/internal_controller.rb', content)
runner.after_review
expect(runner.errors.size).to eq(0)
end
it 'does not remove unused methods if they are except_methods' do
content = <<-EOF
class ExceptableController < ApplicationController
def list; end
end
EOF
runner.prepare('app/controllers/exceptable_controller.rb', content)
runner.review('app/controllers/exceptable_controller.rb', content)
runner.after_review
expect(runner.errors.size).to eq(0)
end
end
context 'assignment' do
it 'does not remove unused methods if call in base class' do
content = <<-EOF
RailsBestPracticesCom::Application.routes.draw do
resources :user, only: :show do; end
end
EOF
runner.prepare('config/routes.rb', content)
application_content = <<-EOF
class ApplicationController
def current_user=(user); end
end
EOF
runner.prepare('app/controllers/application_controller.rb', application_content)
users_content = <<-EOF
class UsersController < ApplicationController
def show
current_user = @user
end
end
EOF
runner.prepare('app/controllers/users_controller.rb', users_content)
runner.review('app/controllers/application_controller.rb', application_content)
runner.review('app/controllers/users_controller.rb', users_content)
runner.after_review
expect(runner.errors.size).to eq(0)
end
end
context 'helper_method' do
it 'removes unused methods if helper method is not called' do
content = <<-EOF
class PostsController < ApplicationController
helper_method :helper_post
protected
def helper_post; end
end
EOF
runner.prepare('app/controllers/posts_controller.rb', content)
runner.review('app/controllers/posts_controller.rb', content)
runner.after_review
expect(runner.errors.size).to eq(1)
expect(runner.errors[0].to_s).to eq(
'app/controllers/posts_controller.rb:4 - remove unused methods (PostsController#helper_post)'
)
end
it 'does not remove unused methods if call helper method in views' do
content = <<-EOF
class PostsController < ApplicationController
helper_method :helper_post
protected
def helper_post; end
end
EOF
runner.prepare('app/controllers/posts_controller.rb', content)
runner.review('app/controllers/posts_controller.rb', content)
content = <<-EOF
<%= helper_post %>
EOF
runner.review('app/views/posts/show.html.erb', content)
runner.after_review
expect(runner.errors.size).to eq(0)
end
it 'does not remove unused methods if call helper method in helpers' do
content = <<-EOF
class PostsController < ApplicationController
helper_method :helper_post
protected
def helper_post; end
end
EOF
runner.prepare('app/controllers/posts_controller.rb', content)
runner.review('app/controllers/posts_controller.rb', content)
content = <<-EOF
module PostsHelper
def new_post
helper_post
end
end
EOF
runner.review('app/helpers/posts_helper.rb', content)
runner.after_review
expect(runner.errors.size).to eq(0)
end
end
context 'delegate to: :controller' do
it 'removes unused methods if delegate method is not called' do
content = <<-EOF
class PostsController < ApplicationController
protected
def helper_post(type); end
end
EOF
runner.prepare('app/controllers/posts_controller.rb', content)
runner.review('app/controllers/posts_controller.rb', content)
content = <<-EOF
module PostsHelper
delegate :helper_post, to: :controller
end
EOF
runner.review('app/helpers/posts_helper.rb', content)
runner.after_review
expect(runner.errors.size).to eq(1)
expect(runner.errors[0].to_s).to eq(
'app/controllers/posts_controller.rb:3 - remove unused methods (PostsController#helper_post)'
)
end
it 'removes unused methods if delegate method is called' do
content = <<-EOF
class PostsController < ApplicationController
protected
def helper_post(type); end
end
EOF
runner.prepare('app/controllers/posts_controller.rb', content)
runner.review('app/controllers/posts_controller.rb', content)
content = <<-EOF
module PostsHelper
delegate :helper_post, to: :controller
end
EOF
runner.review('app/helpers/posts_helper.rb', content)
content = <<-EOF
<%= helper_post("new") %>
EOF
runner.review('app/views/posts/show.html.erb', content)
runner.after_review
expect(runner.errors.size).to eq(0)
end
end
context 'cells' do
it 'removes unused methods' do
content = <<-EOF
class PostsCell < Cell::Rails
def list; end
end
EOF
runner.prepare('app/cells/posts_cell.rb', content)
runner.review('app/cells/posts_cell.rb', content)
runner.after_review
expect(runner.errors.size).to eq(1)
expect(runner.errors[0].to_s).to eq('app/cells/posts_cell.rb:2 - remove unused methods (PostsCell#list)')
end
it 'does not remove unused methods if render_cell' do
content = <<-EOF
class PostsCell < Cell::Rails
def list; end
def display; end
end
EOF
runner.prepare('app/cells/posts_cell.rb', content)
runner.review('app/cells/posts_cell.rb', content)
content = <<-EOF
<%= render_cell :posts, :list %>
<%= render_cell(:posts, :display) %>
EOF
runner.review('app/views/posts/index.html.erb', content)
runner.after_review
expect(runner.errors.size).to eq(0)
end
it 'does not remove unused methods if render with state' do
content = <<-EOF
class PostsCell < Cell::Rails
def list
render state: :show
render(state: :display)
end
def show; end
def display; end
end
EOF
runner.prepare('app/cells/posts_cell.rb', content)
runner.review('app/cells/posts_cell.rb', content)
content = <<-EOF
<%= render_cell :posts, :list %>
EOF
runner.review('app/views/posts/index.html.erb', content)
runner.after_review
expect(runner.errors.size).to eq(0)
end
end
it 'does not remove unused methods' do
route_content = <<-EOF
RailsBestPracticesCom::Application.routes.draw do
namespace :admin do
resources :users, only: :index
end
end
EOF
app_controller_content = <<-EOF
module Admin
class AppController < ApplicationController
def index
@collection = model.all
end
end
end
EOF
users_controller_content = <<-EOF
module Admin
class UsersController < AppController
private
def model
User
end
end
end
EOF
runner.prepare('config/routes.rb', route_content)
runner.prepare('app/controllers/admin/app_controller.rb', app_controller_content)
runner.prepare('app/controllers/admin/users_controller.rb', users_controller_content)
runner.review('app/controllers/admin/app_controller.rb', app_controller_content)
runner.review('app/controllers/admin/users_controller.rb', users_controller_content)
runner.after_review
expect(runner.errors.size).to eq(0)
end
it 'does not check ignored files' do
runner =
Core::Runner.new(
prepares: [Prepares::ControllerPrepare.new, Prepares::RoutePrepare.new],
reviews: described_class.new(ignored_files: /posts_controller/, except_methods: [])
)
content = <<-EOF
RailsBestPracticesCom::Application.routes.draw do
resources :posts do
member do
post 'link_to/:other_id' => 'posts#link_to_post'
post 'extra_update' => 'posts#extra_update'
end
end
end
EOF
runner.prepare('config/routes.rb', content)
content = <<-EOF
class PostsController < ActiveRecord::Base
def show; end
def extra_update; end
def link_to_post; end
protected
def load_post; end
private
def load_user; end
end
EOF
runner.prepare('app/controllers/posts_controller.rb', content)
runner.review('app/controllers/posts_controller.rb', content)
runner.after_review
expect(runner.errors.size).to eq(0)
end
end
end
end
| ruby | MIT | 2ef40880d12ff8ed5f516871133ec569df03b192 | 2026-01-04T15:47:01.660067Z | false |
flyerhzm/rails_best_practices | https://github.com/flyerhzm/rails_best_practices/blob/2ef40880d12ff8ed5f516871133ec569df03b192/spec/rails_best_practices/reviews/dry_bundler_in_capistrano_review_spec.rb | spec/rails_best_practices/reviews/dry_bundler_in_capistrano_review_spec.rb | # frozen_string_literal: true
require 'spec_helper'
module RailsBestPractices
module Reviews
describe DryBundlerInCapistranoReview do
let(:runner) { Core::Runner.new(reviews: described_class.new) }
it 'dries bundler in capistrno' do
content = <<-EOF
namespace :bundler do
task :create_symlink, roles: :app do
shared_dir = File.join(shared_path, 'bundle')
release_dir = File.join(current_release, '.bundle')
run("mkdir -p \#{shared_dir} && ln -s \#{shared_dir} \#{release_dir}")
end
task :bundle_new_release, roles: :app do
bundler.create_symlink
run "cd \#{release_path} && bundle install --without development test"
end
end
after 'deploy:update_code', 'bundler:bundle_new_release'
EOF
runner.review('config/deploy.rb', content)
expect(runner.errors.size).to eq(1)
expect(runner.errors[0].to_s).to eq('config/deploy.rb:1 - dry bundler in capistrano')
end
it 'does not dry bundler in capistrano' do
content = <<-EOF
require 'bundler/capistrano'
EOF
runner.review('config/deploy.rb', content)
expect(runner.errors.size).to eq(0)
end
it 'does not check ignored files' do
runner = Core::Runner.new(reviews: described_class.new(ignored_files: /deploy\.rb/))
content = <<-EOF
namespace :bundler do
task :create_symlink, roles: :app do
shared_dir = File.join(shared_path, 'bundle')
release_dir = File.join(current_release, '.bundle')
run("mkdir -p \#{shared_dir} && ln -s \#{shared_dir} \#{release_dir}")
end
task :bundle_new_release, roles: :app do
bundler.create_symlink
run "cd \#{release_path} && bundle install --without development test"
end
end
after 'deploy:update_code', 'bundler:bundle_new_release'
EOF
runner.review('config/deploy.rb', content)
expect(runner.errors.size).to eq(0)
end
end
end
end
| ruby | MIT | 2ef40880d12ff8ed5f516871133ec569df03b192 | 2026-01-04T15:47:01.660067Z | false |
flyerhzm/rails_best_practices | https://github.com/flyerhzm/rails_best_practices/blob/2ef40880d12ff8ed5f516871133ec569df03b192/spec/rails_best_practices/reviews/replace_instance_variable_with_local_variable_review_spec.rb | spec/rails_best_practices/reviews/replace_instance_variable_with_local_variable_review_spec.rb | # frozen_string_literal: true
require 'spec_helper'
module RailsBestPractices
module Reviews
describe ReplaceInstanceVariableWithLocalVariableReview do
let(:runner) { Core::Runner.new(reviews: described_class.new) }
it 'replaces instance variable with local varialbe' do
content = <<-EOF
<%= @post.title %>
EOF
runner.review('app/views/posts/_post.html.erb', content)
expect(runner.errors.size).to eq(1)
expect(runner.errors[0].to_s).to eq(
'app/views/posts/_post.html.erb:1 - replace instance variable with local variable'
)
end
it 'replaces instance variable with local varialbe in haml file' do
content = <<~EOF
= @post.title
EOF
runner.review('app/views/posts/_post.html.haml', content)
expect(runner.errors.size).to eq(1)
expect(runner.errors[0].to_s).to eq(
'app/views/posts/_post.html.haml:1 - replace instance variable with local variable'
)
end
it 'replaces instance variable with local varialbe in slim file' do
content = <<~EOF
= @post.title
EOF
runner.review('app/views/posts/_post.html.slim', content)
expect(runner.errors.size).to eq(1)
expect(runner.errors[0].to_s).to eq(
'app/views/posts/_post.html.slim:1 - replace instance variable with local variable'
)
end
it 'does not replace instance variable with local varialbe' do
content = <<-EOF
<%= post.title %>
EOF
runner.review('app/views/posts/_post.html.erb', content)
expect(runner.errors.size).to eq(0)
end
it 'does not check ignored files' do
runner = Core::Runner.new(reviews: described_class.new(ignored_files: %r{views/posts}))
content = <<-EOF
<%= @post.title %>
EOF
runner.review('app/views/posts/_post.html.erb', content)
expect(runner.errors.size).to eq(0)
end
end
end
end
| ruby | MIT | 2ef40880d12ff8ed5f516871133ec569df03b192 | 2026-01-04T15:47:01.660067Z | false |
flyerhzm/rails_best_practices | https://github.com/flyerhzm/rails_best_practices/blob/2ef40880d12ff8ed5f516871133ec569df03b192/spec/rails_best_practices/reviews/use_parentheses_in_method_def_review_spec.rb | spec/rails_best_practices/reviews/use_parentheses_in_method_def_review_spec.rb | # frozen_string_literal: true
require 'spec_helper'
module RailsBestPractices
module Reviews
describe UseParenthesesInMethodDefReview do
let(:runner) { Core::Runner.new(reviews: described_class.new) }
it 'finds missing parentheses' do
content = <<-EOF
class PostsController < ApplicationController
def edit foo, bar
end
end
EOF
runner.review('app/controllers/posts_controller.rb', content)
expect(runner.errors.size).to eq(1)
expect(runner.errors[0].to_s).to eq(
'app/controllers/posts_controller.rb:2 - use parentheses around parameters in method definitions'
)
end
it 'finds parentheses with no error' do
content = <<-EOF
class PostsController < ApplicationController
def edit(foo, bar)
end
end
EOF
runner.review('app/controllers/posts_controller.rb', content)
expect(runner.errors.size).to eq(0)
end
it 'does not throw an error without parameters' do
content = <<-EOF
class PostsController < ApplicationController
def edit
end
end
EOF
runner.review('app/controllers/posts_controller.rb', content)
expect(runner.errors.size).to eq(0)
end
it 'does not check ignored files' do
runner = Core::Runner.new(reviews: described_class.new(ignored_files: /posts_controller/))
content = <<-EOF
class PostsController < ApplicationController
def edit foo, bar
end
end
EOF
runner.review('app/controllers/posts_controller.rb', content)
expect(runner.errors.size).to eq(0)
end
end
end
end
| ruby | MIT | 2ef40880d12ff8ed5f516871133ec569df03b192 | 2026-01-04T15:47:01.660067Z | false |
flyerhzm/rails_best_practices | https://github.com/flyerhzm/rails_best_practices/blob/2ef40880d12ff8ed5f516871133ec569df03b192/spec/rails_best_practices/reviews/move_model_logic_into_model_review_spec.rb | spec/rails_best_practices/reviews/move_model_logic_into_model_review_spec.rb | # frozen_string_literal: true
require 'spec_helper'
module RailsBestPractices
module Reviews
describe MoveModelLogicIntoModelReview do
let(:runner) { Core::Runner.new(reviews: described_class.new) }
it 'moves model logic into model' do
content = <<-EOF
class PostsController < ApplicationController
def publish
@post = Post.find(params[:id])
@post.update_attributes(:is_published, true)
@post.approved_by = current_user
if @post.created_at > Time.now - 7.days
@post.popular = 100
else
@post.popular = 0
end
redirect_to post_url(@post)
end
end
EOF
runner.review('app/controllers/posts_controller.rb', content)
expect(runner.errors.size).to eq(1)
expect(runner.errors[0].to_s).to eq(
'app/controllers/posts_controller.rb:2 - move model logic into model (@post use_count > 4)'
)
end
it 'does not move model logic into model with simple model calling' do
content = <<-EOF
class PostsController < ApplicationController
def publish
@post = Post.find(params[:id])
@post.update_attributes(:is_published, true)
@post.approved_by = current_user
redirect_to post_url(@post)
end
end
EOF
runner.review('app/controllers/posts_controller.rb', content)
expect(runner.errors.size).to eq(0)
end
it 'does not move model logic into model with self calling' do
content = <<-EOF
class PostsController < ApplicationController
def publish
self.step1
self.step2
self.step3
self.step4
self.step5
end
end
EOF
runner.review('app/controllers/posts_controller.rb', content)
expect(runner.errors.size).to eq(0)
end
it 'does not check ignored files' do
runner = Core::Runner.new(reviews: described_class.new(ignored_files: %r{app/controllers/posts}))
content = <<-EOF
class PostsController < ApplicationController
def publish
@post = Post.find(params[:id])
@post.update_attributes(:is_published, true)
@post.approved_by = current_user
if @post.created_at > Time.now - 7.days
@post.popular = 100
else
@post.popular = 0
end
redirect_to post_url(@post)
end
end
EOF
runner.review('app/controllers/posts_controller.rb', content)
expect(runner.errors.size).to eq(0)
end
end
end
end
| ruby | MIT | 2ef40880d12ff8ed5f516871133ec569df03b192 | 2026-01-04T15:47:01.660067Z | false |
flyerhzm/rails_best_practices | https://github.com/flyerhzm/rails_best_practices/blob/2ef40880d12ff8ed5f516871133ec569df03b192/spec/rails_best_practices/reviews/move_code_into_model_review_spec.rb | spec/rails_best_practices/reviews/move_code_into_model_review_spec.rb | # frozen_string_literal: true
require 'spec_helper'
module RailsBestPractices
module Reviews
describe MoveCodeIntoModelReview do
let(:runner) { Core::Runner.new(reviews: described_class.new) }
it 'moves code into model' do
content = <<-EOF
<% if current_user && @post.user && (current_user == @post.user || @post.editors.include?(current_user)) %>
<%= link_to 'Edit this post', edit_post_url(@post) %>
<% end %>
EOF
runner.review('app/views/posts/show.html.erb', content)
expect(runner.errors.size).to eq(1)
expect(runner.errors[0].to_s).to eq(
'app/views/posts/show.html.erb:1 - move code into model (@post use_count > 2)'
)
end
it 'moves code into model with haml' do
content = <<~EOF
- if current_user && @post.user && (current_user == @post.user || @post.editors.include?(current_user))
= link_to 'Edit this post', edit_post_url(@post)
EOF
runner.review('app/views/posts/show.html.haml', content)
expect(runner.errors.size).to eq(1)
expect(runner.errors[0].to_s).to eq(
'app/views/posts/show.html.haml:1 - move code into model (@post use_count > 2)'
)
end
it 'moves code into model with slim' do
content = <<~EOF
- if current_user && @post.user && (current_user == @post.user || @post.editors.include?(current_user))
= link_to 'Edit this post', edit_post_url(@post)
EOF
runner.review('app/views/posts/show.html.slim', content)
expect(runner.errors.size).to eq(1)
expect(runner.errors[0].to_s).to eq(
'app/views/posts/show.html.slim:1 - move code into model (@post use_count > 2)'
)
end
it 'moves code into model with if in one line' do
content = <<-EOF
<%= link_to 'Edit this post', edit_post_url(@post) if current_user && @post.user && (current_user == @post.user || @post.editors.include?(current_user)) %>
EOF
runner.review('app/views/posts/show.html.erb', content)
expect(runner.errors.size).to eq(1)
expect(runner.errors[0].to_s).to eq(
'app/views/posts/show.html.erb:1 - move code into model (@post use_count > 2)'
)
end
it "moves code into model with '? :'" do
content = <<-EOF
<%= current_user && @post.user && (current_user == @post.user || @post.editors.include?(current_user)) ? link_to('Edit this post', edit_post_url(@post)) : '' %>
EOF
runner.review('app/views/posts/show.html.erb', content)
expect(runner.errors.size).to eq(1)
expect(runner.errors[0].to_s).to eq(
'app/views/posts/show.html.erb:1 - move code into model (@post use_count > 2)'
)
end
it 'moves code into model only review for current if conditional statement' do
content = <<-EOF
<% if @post.title %>
<% if @post.user %>
<% if @post.description %>
<% end %>
<% end %>
<% end %>
EOF
runner.review('app/views/posts/show.html.erb', content)
expect(runner.errors.size).to eq(0)
end
it 'does not move code into model' do
content = <<-EOF
<% if @post.editable_by?(current_user) %>
<%= link_to 'Edit this post', edit_post_url(@post) %>
<% end %>
EOF
runner.review('app/views/posts/show.html.erb', content)
expect(runner.errors.size).to eq(0)
end
it 'does not move code into model for multiple calls on same variable node' do
content = <<-EOF
<% if !job.company.blank? && job.company.title? %>
<% end %>
EOF
runner.review('app/views/jobs/show.html.erb', content)
expect(runner.errors.size).to eq(0)
end
it 'does not check ignored files' do
runner = Core::Runner.new(reviews: described_class.new(ignored_files: %r{app/views/post}))
content = <<-EOF
<% if current_user && @post.user && (current_user == @post.user || @post.editors.include?(current_user)) %>
<%= link_to 'Edit this post', edit_post_url(@post) %>
<% end %>
EOF
runner.review('app/views/posts/show.html.erb', content)
expect(runner.errors.size).to eq(0)
end
end
end
end
| ruby | MIT | 2ef40880d12ff8ed5f516871133ec569df03b192 | 2026-01-04T15:47:01.660067Z | false |
flyerhzm/rails_best_practices | https://github.com/flyerhzm/rails_best_practices/blob/2ef40880d12ff8ed5f516871133ec569df03b192/spec/rails_best_practices/reviews/overuse_route_customizations_review_spec.rb | spec/rails_best_practices/reviews/overuse_route_customizations_review_spec.rb | # frozen_string_literal: true
require 'spec_helper'
module RailsBestPractices
module Reviews
describe OveruseRouteCustomizationsReview do
let(:runner) { Core::Runner.new(reviews: described_class.new) }
it 'overuses route customizations' do
content = <<-EOF
RailsBestpracticesCom::Application.routes.draw do
resources :posts do
member do
post :create_comment
update :update_comment
delete :delete_comment
end
collection do
get :comments
end
end
end
EOF
runner.review('config/routes.rb', content)
expect(runner.errors.size).to eq(1)
expect(runner.errors[0].to_s).to eq('config/routes.rb:2 - overuse route customizations (customize_count > 3)')
end
it 'overuses route customizations another way' do
content = <<-EOF
RailsBestpracticesCom::Application.routes.draw do
resources :posts do
post :create_comment, on: :member
update :update_comment, on: :member
delete :delete_comment, on: :member
get :comments, on: :collection
end
end
EOF
runner.review('config/routes.rb', content)
expect(runner.errors.size).to eq(1)
expect(runner.errors[0].to_s).to eq('config/routes.rb:2 - overuse route customizations (customize_count > 3)')
end
it 'does not overuse route customizations without customization' do
content = <<-EOF
RailsBestpracticesCom::Application.routes.draw do
resources :posts
end
EOF
runner.review('config/routes.rb', content)
expect(runner.errors.size).to eq(0)
end
it 'does not overuse route customizations when customize route is only one' do
content = <<-EOF
RailsBestpracticesCom::Application.routes.draw do
resources :posts do
member do
post :vote
end
end
end
EOF
runner.review('config/routes.rb', content)
expect(runner.errors.size).to eq(0)
end
it 'does not check ignored files' do
runner = Core::Runner.new(reviews: described_class.new(ignored_files: %r{config/routes\.rb}))
content = <<-EOF
ActionController::Routing::Routes.draw do |map|
map.resources :posts, member: { comments: :get,
create_comment: :post,
update_comment: :update,
delete_comment: :delete }
end
EOF
runner.review('config/routes.rb', content)
expect(runner.errors.size).to eq(0)
end
end
end
end
| ruby | MIT | 2ef40880d12ff8ed5f516871133ec569df03b192 | 2026-01-04T15:47:01.660067Z | false |
flyerhzm/rails_best_practices | https://github.com/flyerhzm/rails_best_practices/blob/2ef40880d12ff8ed5f516871133ec569df03b192/spec/rails_best_practices/reviews/use_turbo_sprockets_rails3_review_spec.rb | spec/rails_best_practices/reviews/use_turbo_sprockets_rails3_review_spec.rb | # frozen_string_literal: true
require 'spec_helper'
module RailsBestPractices
module Reviews
describe UseTurboSprocketsRails3Review do
let(:runner) { Core::Runner.new(prepares: Prepares::GemfilePrepare.new, reviews: described_class.new) }
it 'uses turbo-sprockets-rails3' do
content = <<~EOF
GEM
remote: https://rubygems.org
specs:
rails (3.2.13)
actionmailer (= 3.2.13)
actionpack (= 3.2.13)
activerecord (= 3.2.13)
activeresource (= 3.2.13)
activesupport (= 3.2.13)
bundler (~> 1.0)
railties (= 3.2.13)
EOF
runner.prepare('Gemfile.lock', content)
content = <<-EOF
load 'deploy' if respond_to?(:namespace)
load 'deploy/assets'
load 'config/deploy'
EOF
runner.review('Capfile', content)
expect(runner.errors.size).to eq(1)
expect(runner.errors[0].to_s).to eq('Capfile:2 - speed up assets precompile with turbo-sprockets-rails3')
end
it 'does not use turbo-sprockets-rails3 with turbo-sprockets-rails3 gem' do
content = <<~EOF
GEM
remote: https://rubygems.org
specs:
rails (3.2.13)
actionmailer (= 3.2.13)
actionpack (= 3.2.13)
activerecord (= 3.2.13)
activeresource (= 3.2.13)
activesupport (= 3.2.13)
bundler (~> 1.0)
railties (= 3.2.13)
turbo-sprockets-rails3 (0.3.6)
railties (> 3.2.8, < 4.0.0)
sprockets (>= 2.0.0)
EOF
runner.prepare('Gemfile.lock', content)
content = <<-EOF
load 'deploy' if respond_to?(:namespace)
load 'deploy/assets'
load 'config/deploy'
EOF
runner.review('Capfile', content)
expect(runner.errors.size).to eq(0)
end
it 'does not use turbo-sprockets-rails3 without deploy/assets' do
content = <<-EOF
load 'deploy' if respond_to?(:namespace)
#load 'deploy/assets'
load 'config/deploy'
EOF
runner.review('Capfile', content)
expect(runner.errors.size).to eq(0)
end
it 'does not use turbo-sprockets-rails3 with rails4 gem' do
content = <<~EOF
GEM
remote: https://rubygems.org
specs:
rails (4.0.0)
actionmailer (= 4.0.0)
actionpack (= 4.0.0)
activerecord (= 4.0.0)
activeresource (= 4.0.0)
activesupport (= 4.0.0)
bundler (~> 1.0)
railties (= 3.2.13)
EOF
runner.prepare('Gemfile.lock', content)
content = <<-EOF
load 'deploy' if respond_to?(:namespace)
load 'deploy/assets'
load 'config/deploy'
EOF
runner.review('Capfile', content)
expect(runner.errors.size).to eq(0)
end
it 'does not check ignored files' do
runner =
Core::Runner.new(
prepares: Prepares::GemfilePrepare.new, reviews: described_class.new(ignored_files: /Capfile/)
)
content = <<~EOF
GEM
remote: https://rubygems.org
specs:
rails (3.2.13)
actionmailer (= 3.2.13)
actionpack (= 3.2.13)
activerecord (= 3.2.13)
activeresource (= 3.2.13)
activesupport (= 3.2.13)
bundler (~> 1.0)
railties (= 3.2.13)
EOF
runner.prepare('Gemfile.lock', content)
content = <<-EOF
load 'deploy' if respond_to?(:namespace)
load 'deploy/assets'
load 'config/deploy'
EOF
runner.review('Capfile', content)
expect(runner.errors.size).to eq(0)
end
end
end
end
| ruby | MIT | 2ef40880d12ff8ed5f516871133ec569df03b192 | 2026-01-04T15:47:01.660067Z | false |
flyerhzm/rails_best_practices | https://github.com/flyerhzm/rails_best_practices/blob/2ef40880d12ff8ed5f516871133ec569df03b192/spec/rails_best_practices/reviews/restrict_auto_generated_routes_review_spec.rb | spec/rails_best_practices/reviews/restrict_auto_generated_routes_review_spec.rb | # frozen_string_literal: true
require 'spec_helper'
module RailsBestPractices
module Reviews
describe RestrictAutoGeneratedRoutesReview do
let(:runner) { Core::Runner.new(prepares: Prepares::ControllerPrepare.new, reviews: described_class.new) }
describe 'resources' do
before do
content = <<-EOF
class PostsController < ApplicationController
def show; end
def new; end
def create; end
def edit; end
def update; end
def destroy; end
end
EOF
runner.prepare('app/controllers/posts_controller.rb', content)
end
it 'restricts auto-generated routes' do
content = <<-EOF
RailsBestPracticesCom::Application.routes.draw do
resources :posts
end
EOF
runner.review('config/routes.rb', content)
expect(runner.errors.size).to eq(1)
expect(runner.errors[0].to_s).to eq(
'config/routes.rb:2 - restrict auto-generated routes posts (except: [:index])'
)
end
it 'does not restrict auto-generated routes with only' do
content = <<-EOF
RailsBestPracticesCom::Application.routes.draw do
resources :posts, only: %w(show new create edit update destroy)
end
EOF
runner.review('config/routes.rb', content)
expect(runner.errors.size).to eq(0)
end
it 'does not restrict auto-generated routes with except' do
content = <<-EOF
RailsBestPracticesCom::Application.routes.draw do
resources :posts, except: :index
end
EOF
runner.review('config/routes.rb', content)
expect(runner.errors.size).to eq(0)
end
describe 'specify a controller' do
it 'restricts auto-generated routes' do
content = <<-EOF
RailsBestPracticesCom::Application.routes.draw do
resources :articles, controller: "posts"
end
EOF
runner.review('config/routes.rb', content)
expect(runner.errors.size).to eq(1)
expect(runner.errors[0].to_s).to eq(
'config/routes.rb:2 - restrict auto-generated routes articles (except: [:index])'
)
end
end
describe 'namespace' do
before do
content = <<-EOF
class Admin::CommentsController < ApplicationController
def show; end
def new; end
def create; end
def edit; end
def update; end
def destroy; end
end
EOF
runner.prepare('app/controllers/admin/comments_controller.rb', content)
end
it 'restricts auto-generated routes' do
content = <<-EOF
RailsBestPracticesCom::Application.routes.draw do
namespace :admin do
resources :comments
end
end
EOF
runner.review('config/routes.rb', content)
expect(runner.errors.size).to eq(1)
expect(runner.errors[0].to_s).to eq(
'config/routes.rb:3 - restrict auto-generated routes admin/comments (except: [:index])'
)
end
it 'restricts auto-generated routes with scope :module' do
content = <<-EOF
RailsBestPracticesCom::Application.routes.draw do
scope module: :admin do
resources :comments
end
end
EOF
runner.review('config/routes.rb', content)
expect(runner.errors.size).to eq(1)
expect(runner.errors[0].to_s).to eq(
'config/routes.rb:3 - restrict auto-generated routes admin/comments (except: [:index])'
)
end
it 'restricts auto-generated routes with resources :module' do
content = <<-EOF
RailsBestPracticesCom::Application.routes.draw do
resources :comments, module: :admin
end
EOF
runner.review('config/routes.rb', content)
expect(runner.errors.size).to eq(1)
expect(runner.errors[0].to_s).to eq(
'config/routes.rb:2 - restrict auto-generated routes admin/comments (except: [:index])'
)
end
end
describe 'nested routes' do
before do
content = <<-EOF
class CommentsController < ApplicationController
def index; end
def show; end
def new; end
def create; end
def edit; end
def update; end
def destroy; end
end
EOF
runner.prepare('app/controllers/comments_controller.rb', content)
end
it 'restricts auto-generated routes' do
content = <<-EOF
RailsBestPracticesCom::Application.routes.draw do
resources :posts do
resources :comments
end
end
EOF
runner.review('config/routes.rb', content)
expect(runner.errors.size).to eq(1)
expect(runner.errors[0].to_s).to eq(
'config/routes.rb:2 - restrict auto-generated routes posts (except: [:index])'
)
end
it 'does not restrict auto-generated routes with only' do
content = <<-EOF
RailsBestPracticesCom::Application.routes.draw do
resources :posts, only: %w(show new create edit update destroy) do
resources :comments
end
end
EOF
runner.review('config/routes.rb', content)
expect(runner.errors.size).to eq(0)
end
it 'does not restrict auto-generated routes with except' do
content = <<-EOF
RailsBestPracticesCom::Application.routes.draw do
resources :posts, except: :index do
resources :comments
end
end
EOF
runner.review('config/routes.rb', content)
expect(runner.errors.size).to eq(0)
end
end
end
describe 'resource' do
before do
content = <<-EOF
class AccountsController < ApplicationController
def show; end
def new; end
def create; end
def edit; end
def update; end
end
EOF
runner.prepare('app/controllers/accounts_controller.rb', content)
end
it 'restricts auto-generated routes' do
content = <<-EOF
ActionController::Routing::Routes.draw do |map|
map.resource :account
end
EOF
runner.review('config/routes.rb', content)
expect(runner.errors.size).to eq(1)
expect(runner.errors[0].to_s).to eq(
'config/routes.rb:2 - restrict auto-generated routes account (except: [:destroy])'
)
end
it 'does not restrict auto-generated routes with only' do
content = <<-EOF
ActionController::Routing::Routes.draw do |map|
map.resource :account, only: %w(show new create edit update)
end
EOF
runner.review('config/routes.rb', content)
expect(runner.errors.size).to eq(0)
end
it 'does not restrict auto-generated routes with except' do
content = <<-EOF
ActionController::Routing::Routes.draw do |map|
map.resource :account, except: :destroy
end
EOF
runner.review('config/routes.rb', content)
expect(runner.errors.size).to eq(0)
end
it 'does not check ignored files' do
runner =
Core::Runner.new(
prepares: Prepares::ControllerPrepare.new,
reviews: described_class.new(ignored_files: %r{config/routes\.rb})
)
content = <<-EOF
ActionController::Routing::Routes.draw do |map|
map.resource :account
end
EOF
runner.review('config/routes.rb', content)
expect(runner.errors.size).to eq(0)
end
end
context 'api_only = true' do
let(:runner) do
Core::Runner.new(
prepares: [Prepares::ConfigPrepare.new, Prepares::ControllerPrepare.new], reviews: described_class.new
)
end
before do
content = <<-EOF
module RailsBestPracticesCom
class Application < Rails::Application
config.api_only = true
end
end
EOF
runner.prepare('config/application.rb', content)
content = <<-EOF
class PostsController < ApplicationController
def show; end
def create; end
def update; end
def destroy; end
end
EOF
runner.prepare('app/controllers/posts_controller.rb', content)
end
it 'restricts auto-generated routes' do
content = <<-EOF
RailsBestPracticesCom::Application.routes.draw do
resources :posts
end
EOF
runner.review('config/routes.rb', content)
expect(runner.errors.size).to eq(1)
expect(runner.errors[0].to_s).to eq(
'config/routes.rb:2 - restrict auto-generated routes posts (except: [:index])'
)
end
it 'does not restrict auto-generated routes with only' do
content = <<-EOF
RailsBestPracticesCom::Application.routes.draw do
resources :posts, only: %w(show create update destroy)
end
EOF
runner.review('config/routes.rb', content)
expect(runner.errors.size).to eq(0)
end
end
end
end
end
| ruby | MIT | 2ef40880d12ff8ed5f516871133ec569df03b192 | 2026-01-04T15:47:01.660067Z | false |
flyerhzm/rails_best_practices | https://github.com/flyerhzm/rails_best_practices/blob/2ef40880d12ff8ed5f516871133ec569df03b192/spec/rails_best_practices/reviews/use_observer_review_spec.rb | spec/rails_best_practices/reviews/use_observer_review_spec.rb | # frozen_string_literal: true
require 'spec_helper'
module RailsBestPractices
module Reviews
describe UseObserverReview do
let(:runner) { Core::Runner.new(prepares: Prepares::MailerPrepare.new, reviews: described_class.new) }
before do
content = <<-EOF
class ProjectMailer < ActionMailer::Base
end
EOF
runner.prepare('app/models/project_mailer.rb', content)
end
it 'uses observer' do
content = <<-EOF
class Project < ActiveRecord::Base
after_create :send_create_notification
private
def send_create_notification
self.members.each do |member|
ProjectMailer.notification(self, member).deliver
end
end
end
EOF
runner.review('app/models/project.rb', content)
expect(runner.errors.size).to eq(1)
expect(runner.errors[0].to_s).to eq('app/models/project.rb:5 - use observer')
end
it 'does not use observer without callback' do
content = <<-EOF
class Project < ActiveRecord::Base
private
def send_create_notification
self.members.each do |member|
ProjectMailer.notification(self, member).deliver
end
end
end
EOF
runner.review('app/models/project.rb', content)
expect(runner.errors.size).to eq(0)
end
it 'uses observer with two after_create' do
content = <<-EOF
class Project < ActiveRecord::Base
after_create :send_create_notification, :update_author
private
def send_create_notification
self.members.each do |member|
ProjectMailer.notification(self, member).deliver
end
end
def update_author
end
end
EOF
runner.review('app/models/project.rb', content)
expect(runner.errors.size).to eq(1)
expect(runner.errors[0].to_s).to eq('app/models/project.rb:5 - use observer')
end
it 'does not raise when initiate an object in callback' do
content = <<-EOF
class Project < ActiveRecord::Base
after_create ProjectMailer.new
end
EOF
expect { runner.review('app/models/project.rb', content) }.not_to raise_error
end
end
end
end
| ruby | MIT | 2ef40880d12ff8ed5f516871133ec569df03b192 | 2026-01-04T15:47:01.660067Z | false |
flyerhzm/rails_best_practices | https://github.com/flyerhzm/rails_best_practices/blob/2ef40880d12ff8ed5f516871133ec569df03b192/spec/rails_best_practices/reviews/use_say_with_time_in_migrations_review_spec.rb | spec/rails_best_practices/reviews/use_say_with_time_in_migrations_review_spec.rb | # frozen_string_literal: true
require 'spec_helper'
module RailsBestPractices
module Reviews
describe UseSayWithTimeInMigrationsReview do
let(:runner) { Core::Runner.new(reviews: described_class.new) }
it 'uses say with time in migrations' do
content = <<-EOF
def self.up
User.find_each do |user|
user.first_name, user.last_name = user.full_name.split(' ')
user.save
end
end
EOF
runner.review('db/migrate/20101010080658_update_users.rb', content)
expect(runner.errors.size).to eq(1)
expect(runner.errors[0].to_s).to eq(
'db/migrate/20101010080658_update_users.rb:2 - use say with time in migrations'
)
end
it 'uses say with time in migrations with create_table' do
content = <<-EOF
def self.up
create_table :users do |t|
t.string :login
t.timestamps
end
User.find_each do |user|
user.first_name, user.last_name = user.full_name.split(' ')
user.save
end
end
EOF
runner.review('db/migrate/20101010080658_update_users.rb', content)
expect(runner.errors.size).to eq(1)
expect(runner.errors[0].to_s).to eq(
'db/migrate/20101010080658_update_users.rb:7 - use say with time in migrations'
)
end
it 'does not use say with time in migrations' do
content = <<-EOF
def self.up
say_with_time("Initialize first_name and last_name for users") do
User.find_each do |user|
user.first_name, user.last_name = user.full_name.split(' ')
user.save
say(user.id + " was updated.")
end
end
end
EOF
runner.review('db/migrate/20101010080658_update_users.rb', content)
expect(runner.errors.size).to eq(0)
end
it 'does not use say with time in migrations when not first code line' do
content = <<-EOF
def self.up
User.find_each do |user|
say_with_time 'Updating user with latest data' do
user.do_time_consuming_stuff
end
end
end
EOF
runner.review('db/migrate/20101010080658_update_users.rb', content)
expect(runner.errors.size).to eq(0)
end
it 'does not use say with time when default migration message' do
content = <<-EOF
def self.up
create_table :users do |t|
t.string :login
t.string :email
t.timestamps
end
end
EOF
runner.review('db/migrate/20101010080658_create_users.rb', content)
expect(runner.errors.size).to eq(0)
end
it 'does not raise an error' do
content = <<-EOF
class AddAdmin < ActiveRecord::Migration
class Person < ActiveRecord::Base
end
class Blog < ActiveRecord::Base
end
def self.up
add_column :people, :admin, :boolean, default: false, null: false
add_column :people, :deactivated, :boolean,
default: false, null: false
key = Crypto::Key.from_file("\#{RAILS_ROOT}/rsa_key.pub")
person = Person.new(email: "admin@example.com",
name: "admin",
crypted_password: key.encrypt("admin"),
description: "")
person.admin = true
person.save!
Blog.create(person_id: person.id)
end
def self.down
remove_column :people, :deactivated
Person.delete(Person.find_by_name("admin"))
remove_column :people, :admin
end
end
EOF
runner.review('db/migrate/20101010080658_create_users.rb', content)
expect(runner.errors.size).to eq(3)
end
it 'does not check ignored files' do
runner = Core::Runner.new(reviews: described_class.new(ignored_files: /20101010080658_update_users/))
content = <<-EOF
def self.up
User.find_each do |user|
user.first_name, user.last_name = user.full_name.split(' ')
user.save
end
end
EOF
runner.review('db/migrate/20101010080658_update_users.rb', content)
expect(runner.errors.size).to eq(0)
end
end
end
end
| ruby | MIT | 2ef40880d12ff8ed5f516871133ec569df03b192 | 2026-01-04T15:47:01.660067Z | false |
flyerhzm/rails_best_practices | https://github.com/flyerhzm/rails_best_practices/blob/2ef40880d12ff8ed5f516871133ec569df03b192/spec/rails_best_practices/reviews/move_code_into_helper_review_spec.rb | spec/rails_best_practices/reviews/move_code_into_helper_review_spec.rb | # frozen_string_literal: true
require 'spec_helper'
module RailsBestPractices
module Reviews
describe MoveCodeIntoHelperReview do
let(:runner) { Core::Runner.new(reviews: described_class.new('array_count' => 2)) }
it 'moves code into helper' do
content = <<-EOF
<%= select_tag :state, options_for_select( [[t(:draft), "draft"],
[t(:published), "published"]],
params[:default_state] ) %>
EOF
runner.review('app/views/posts/show.html.erb', content)
expect(runner.errors.size).to eq(1)
expect(runner.errors[0].to_s).to eq(
'app/views/posts/show.html.erb:1 - move code into helper (array_count >= 2)'
)
end
it 'does not move code into helper with simple arguments' do
content = <<-EOF
<%= select_tag :state, options_for_select( Post.STATES ) %>
EOF
runner.review('app/views/posts/show.html.erb', content)
expect(runner.errors.size).to eq(0)
end
it 'does not check ignored files' do
runner =
Core::Runner.new(
reviews: MoveCodeIntoControllerReview.new('array_count' => 2, 'ignored_files' => %r{app/views/post})
)
content = <<-EOF
<%= select_tag :state, options_for_select( [[t(:draft), "draft"],
[t(:published), "published"]],
params[:default_state] ) %>
EOF
runner.review('app/views/posts/show.html.erb', content)
expect(runner.errors.size).to eq(0)
end
end
end
end
| ruby | MIT | 2ef40880d12ff8ed5f516871133ec569df03b192 | 2026-01-04T15:47:01.660067Z | false |
flyerhzm/rails_best_practices | https://github.com/flyerhzm/rails_best_practices/blob/2ef40880d12ff8ed5f516871133ec569df03b192/spec/rails_best_practices/reviews/move_code_into_controller_review_spec.rb | spec/rails_best_practices/reviews/move_code_into_controller_review_spec.rb | # frozen_string_literal: true
require 'spec_helper'
module RailsBestPractices
module Reviews
describe MoveCodeIntoControllerReview do
let(:runner) { Core::Runner.new(reviews: described_class.new) }
it 'moves code into controller for method call' do
content = <<-EOF
<% Post.find(:all).each do |post| %>
<%=h post.title %>
<%=h post.content %>
<% end %>
EOF
runner.review('app/views/posts/index.html.erb', content)
expect(runner.errors.size).to eq(1)
expect(runner.errors[0].to_s).to eq('app/views/posts/index.html.erb:1 - move code into controller')
end
it 'moves code into controller for assign' do
content = <<-EOF
<% @posts = Post.all %>
<% @posts.each do |post| %>
<%=h post.title %>
<%=h post.content %>
<% end %>
EOF
runner.review('app/views/posts/index.html.erb', content)
expect(runner.errors.size).to eq(1)
expect(runner.errors[0].to_s).to eq('app/views/posts/index.html.erb:1 - move code into controller')
end
it 'does not move code into controller' do
content = <<-EOF
<% @posts.each do |post| %>
<%=h post.title %>
<%=h post.content %>
<% end %>
EOF
runner.review('app/views/posts/index.html.erb', content)
expect(runner.errors.size).to eq(0)
end
it 'does not check ignored files' do
runner = Core::Runner.new(reviews: described_class.new(ignored_files: %r{app/views/post}))
content = <<-EOF
<% Post.find(:all).each do |post| %>
<%=h post.title %>
<%=h post.content %>
<% end %>
EOF
runner.review('app/views/posts/index.html.erb', content)
expect(runner.errors.size).to eq(0)
end
end
end
end
| ruby | MIT | 2ef40880d12ff8ed5f516871133ec569df03b192 | 2026-01-04T15:47:01.660067Z | false |
flyerhzm/rails_best_practices | https://github.com/flyerhzm/rails_best_practices/blob/2ef40880d12ff8ed5f516871133ec569df03b192/spec/rails_best_practices/reviews/hash_syntax_review_spec.rb | spec/rails_best_practices/reviews/hash_syntax_review_spec.rb | # frozen_string_literal: true
require 'spec_helper'
module RailsBestPractices
module Reviews
describe HashSyntaxReview do
let(:runner) { Core::Runner.new(reviews: described_class.new) }
it 'finds 1.8 Hash with symbol' do
content = <<-EOF
class User < ActiveRecord::Base
CONST = { :foo => :bar }
end
EOF
runner.review('app/models/user.rb', content)
expect(runner.errors.size).to eq(1)
expect(runner.errors[0].to_s).to eq('app/models/user.rb:2 - change Hash Syntax to 1.9')
end
it 'does not find 1.8 Hash with string' do
content = <<-EOF
class User < ActiveRecord::Base
CONST = { "foo" => "bar" }
end
EOF
runner.review('app/models/user.rb', content)
expect(runner.errors.size).to eq(0)
end
it 'does not alert on 1.9 Syntax' do
content = <<-EOF
class User < ActiveRecord::Base
CONST = { foo: :bar }
end
EOF
runner.review('app/models/user.rb', content)
expect(runner.errors.size).to eq(0)
end
it 'ignores haml_out' do
content = <<~EOF
%div{ class: "foo1" }
.div{ class: "foo2" }
#div{ class: "foo3" }
EOF
runner.review('app/views/files/show.html.haml', content)
expect(runner.errors.size).to eq(0)
end
it 'does not consider hash with array key' do
content = <<-EOF
transition [:unverified, :verified] => :deleted
EOF
runner.review('app/models/post.rb', content)
expect(runner.errors.size).to eq(0)
end
it 'does not consider hash with charaters not valid for symbol' do
content = <<-EOF
receiver.stub(:` => 'Error')
EOF
runner.review('app/models/post.rb', content)
expect(runner.errors.size).to eq(0)
end
it 'does not check ignored files' do
runner = Core::Runner.new(reviews: described_class.new(ignored_files: /user/))
content = <<-EOF
class User < ActiveRecord::Base
CONST = { :foo => :bar }
end
EOF
runner.review('app/models/user.rb', content)
expect(runner.errors.size).to eq(0)
end
end
end
end
| ruby | MIT | 2ef40880d12ff8ed5f516871133ec569df03b192 | 2026-01-04T15:47:01.660067Z | false |
flyerhzm/rails_best_practices | https://github.com/flyerhzm/rails_best_practices/blob/2ef40880d12ff8ed5f516871133ec569df03b192/spec/rails_best_practices/reviews/check_destroy_return_value_review_spec.rb | spec/rails_best_practices/reviews/check_destroy_return_value_review_spec.rb | # frozen_string_literal: true
require 'spec_helper'
module RailsBestPractices
module Reviews
describe CheckDestroyReturnValueReview do
let(:runner) { Core::Runner.new(reviews: described_class.new) }
describe 'check_destroy_return_value' do
it 'warns you if you fail to check the destroy return value' do
content = <<-EOF
def my_method
post = Posts.create do |p|
p.title = "foo"
end
post.destroy
end
EOF
runner.review('app/helpers/posts_helper.rb', content)
expect(runner.errors.size).to eq(1)
expect(runner.errors[0].to_s).to eq(
"app/helpers/posts_helper.rb:5 - check 'destroy' return value or use 'destroy!'"
)
end
it 'allows destroy return value if assigned to a var' do
content = <<-EOF
def my_method
post = Posts.create do |p|
p.title = "foo"
end
check_this_later = post.destroy
end
EOF
runner.review('app/helpers/posts_helper.rb', content)
expect(runner.errors.size).to eq(0)
end
it 'allows destroy return value used in if' do
content = <<-EOF
def my_method
post = Posts.create do |p|
p.title = "foo"
end
if post.destroy
"OK"
else
raise "could not delete"
end
end
EOF
runner.review('app/helpers/posts_helper.rb', content)
expect(runner.errors.size).to eq(0)
end
it 'allows destroy return value used in elsif' do
content = <<-EOF
def my_method
post = Posts.create do |p|
p.title = "foo"
end
if current_user
"YES"
elsif post.destroy
"OK"
else
raise "could not delete"
end
end
EOF
runner.review('app/helpers/posts_helper.rb', content)
expect(runner.errors.size).to eq(0)
end
it 'allows destroy return value used in unless' do
content = <<-EOF
def my_method
unless @post.destroy
raise "could not destroy"
end
end
EOF
runner.review('app/helpers/posts_helper.rb', content)
expect(runner.errors.size).to eq(0)
end
it 'allows destroy return value used in if_mod' do
content = <<-EOF
def my_method
post = Posts.create do |p|
p.title = "foo"
end
"OK" if post.destroy
end
EOF
runner.review('app/helpers/posts_helper.rb', content)
expect(runner.errors.size).to eq(0)
end
it 'allows destroy return value used in unless_mod' do
content = <<-EOF
def my_method
post = Posts.create do |p|
p.title = "foo"
end
"NO" unless post.destroy
end
EOF
runner.review('app/helpers/posts_helper.rb', content)
expect(runner.errors.size).to eq(0)
end
it 'allows destroy return value used in unless with &&' do
content = <<-EOF
def my_method
unless some_method(1) && other_method(2) && @post.destroy
raise "could not destroy"
end
end
EOF
runner.review('app/helpers/posts_helper.rb', content)
expect(runner.errors.size).to eq(0)
end
it 'allows destroy!' do
content = <<-EOF
def my_method
post = Posts.create do |p|
p.title = "foo"
end
post.destroy!
end
EOF
runner.review('app/helpers/posts_helper.rb', content)
expect(runner.errors.size).to eq(0)
end
end
it 'does not check ignored files' do
runner = Core::Runner.new(reviews: described_class.new(ignored_files: /helpers/))
content = <<-EOF
def my_method
post = Posts.create do |p|
p.title = "foo"
end
post.destroy
end
EOF
runner.review('app/helpers/posts_helper.rb', content)
expect(runner.errors.size).to eq(0)
end
end
end
end
| ruby | MIT | 2ef40880d12ff8ed5f516871133ec569df03b192 | 2026-01-04T15:47:01.660067Z | false |
flyerhzm/rails_best_practices | https://github.com/flyerhzm/rails_best_practices/blob/2ef40880d12ff8ed5f516871133ec569df03b192/spec/rails_best_practices/reviews/move_finder_to_named_scope_review_spec.rb | spec/rails_best_practices/reviews/move_finder_to_named_scope_review_spec.rb | # frozen_string_literal: true
require 'spec_helper'
module RailsBestPractices
module Reviews
describe MoveFinderToNamedScopeReview do
let(:runner) { Core::Runner.new(reviews: described_class.new) }
it 'moves finder to named_scope' do
content = <<-EOF
class PostsController < ActionController::Base
def index
@public_posts = Post.find(:all, conditions: { state: 'public' },
limit: 10,
order: 'created_at desc')
@draft_posts = Post.find(:all, conditions: { state: 'draft' },
limit: 10,
order: 'created_at desc')
end
end
EOF
runner.review('app/controllers/posts_controller.rb', content)
expect(runner.errors.size).to eq(2)
expect(runner.errors[0].to_s).to eq('app/controllers/posts_controller.rb:3 - move finder to named_scope')
expect(runner.errors[1].to_s).to eq('app/controllers/posts_controller.rb:7 - move finder to named_scope')
end
it 'does not move simple finder' do
content = <<-EOF
class PostsController < ActionController::Base
def index
@all_posts = Post.find(:all)
@another_all_posts = Post.all
@first_post = Post.find(:first)
@another_first_post = Post.first
@last_post = Post.find(:last)
@another_last_post = Post.last
end
end
EOF
runner.review('app/controllers/posts_controller.rb', content)
expect(runner.errors.size).to eq(0)
end
it 'does not move namd_scope' do
content = <<-EOF
class PostsController < ActionController::Base
def index
@public_posts = Post.published
@draft_posts = Post.draft
end
end
EOF
runner.review('app/controllers/posts_controller.rb', content)
expect(runner.errors.size).to eq(0)
end
it 'does not review model file' do
content = <<-EOF
class Post < ActiveRecord::Base
def published
Post.find(:all, conditions: { state: 'public' },
limit: 10, order: 'created_at desc')
end
def published
Post.find(:all, conditions: { state: 'draft' },
limit: 10, order: 'created_at desc')
end
end
EOF
runner.review('app/model/post.rb', content)
expect(runner.errors.size).to eq(0)
end
it 'does not check ignored files' do
runner = Core::Runner.new(reviews: described_class.new(ignored_files: %r{app/controllers/posts}))
content = <<-EOF
class PostsController < ActionController::Base
def index
@public_posts = Post.find(:all, conditions: { state: 'public' },
limit: 10,
order: 'created_at desc')
@draft_posts = Post.find(:all, conditions: { state: 'draft' },
limit: 10,
order: 'created_at desc')
end
end
EOF
runner.review('app/controllers/posts_controller.rb', content)
expect(runner.errors.size).to eq(0)
end
end
end
end
| ruby | MIT | 2ef40880d12ff8ed5f516871133ec569df03b192 | 2026-01-04T15:47:01.660067Z | false |
flyerhzm/rails_best_practices | https://github.com/flyerhzm/rails_best_practices/blob/2ef40880d12ff8ed5f516871133ec569df03b192/spec/rails_best_practices/reviews/use_scope_access_review_spec.rb | spec/rails_best_practices/reviews/use_scope_access_review_spec.rb | # frozen_string_literal: true
require 'spec_helper'
module RailsBestPractices
module Reviews
describe UseScopeAccessReview do
let(:runner) { Core::Runner.new(reviews: described_class.new) }
context 'if' do
it 'uses scope access' do
content = <<-EOF
class PostsController < ApplicationController
def edit
@post = Post.find(params[:id])
if @post.user != current_user
flash[:warning] = 'Access Denied'
redirect_to posts_url
end
end
end
EOF
runner.review('app/controllers/posts_controller.rb', content)
expect(runner.errors.size).to eq(1)
expect(runner.errors[0].to_s).to eq('app/controllers/posts_controller.rb:5 - use scope access')
end
it 'uses scope access with if in one line' do
content = <<-EOF
class PostsController < ApplicationController
def edit
@post = Post.find(params[:id])
redirect_to posts_url if @post.user != current_user
end
end
EOF
runner.review('app/controllers/posts_controller.rb', content)
expect(runner.errors.size).to eq(1)
expect(runner.errors[0].to_s).to eq('app/controllers/posts_controller.rb:5 - use scope access')
end
it "uses scope access with '? :'" do
content = <<-EOF
class PostsController < ApplicationController
def edit
@post = Post.find(params[:id])
@post.user != current_user ? redirect_to(posts_url) : render
end
end
EOF
runner.review('app/controllers/posts_controller.rb', content)
expect(runner.errors.size).to eq(1)
expect(runner.errors[0].to_s).to eq('app/controllers/posts_controller.rb:5 - use scope access')
end
it 'uses scope access by comparing with id' do
content = <<-EOF
class PostsController < ApplicationController
def edit
@post = Post.find(params[:id])
if @post.user_id != current_user.id
flash[:warning] = 'Access Denied'
redirect_to posts_url
end
end
end
EOF
runner.review('app/controllers/posts_controller.rb', content)
expect(runner.errors.size).to eq(1)
expect(runner.errors[0].to_s).to eq('app/controllers/posts_controller.rb:5 - use scope access')
end
it 'uses scope access with current_user ==' do
content = <<-EOF
class PostsController < ApplicationController
def edit
@post = Post.find(params[:id])
if current_user != @post.user
flash[:warning] = 'Access Denied'
redirect_to posts_url
end
end
end
EOF
runner.review('app/controllers/posts_controller.rb', content)
expect(runner.errors.size).to eq(1)
expect(runner.errors[0].to_s).to eq('app/controllers/posts_controller.rb:5 - use scope access')
end
it 'uses scope access by current_user.id ==' do
content = <<-EOF
class PostsController < ApplicationController
def edit
@post = Post.find(params[:id])
if current_user.id != @post.user_id
flash[:warning] = 'Access Denied'
redirect_to posts_url
end
end
end
EOF
runner.review('app/controllers/posts_controller.rb', content)
expect(runner.errors.size).to eq(1)
expect(runner.errors[0].to_s).to eq('app/controllers/posts_controller.rb:5 - use scope access')
end
end
context 'unless' do
it 'uses scope access' do
content = <<-EOF
class PostsController < ApplicationController
def edit
@post = Post.find(params[:id])
unless @post.user == current_user
flash[:warning] = 'Access Denied'
redirect_to posts_url
end
end
end
EOF
runner.review('app/controllers/posts_controller.rb', content)
expect(runner.errors.size).to eq(1)
expect(runner.errors[0].to_s).to eq('app/controllers/posts_controller.rb:5 - use scope access')
end
it 'uses scope access by comparing with id' do
content = <<-EOF
class PostsController < ApplicationController
def edit
@post = Post.find(params[:id])
unless @post.user_id == current_user.id
flash[:warning] = 'Access Denied'
redirect_to posts_url
end
end
end
EOF
runner.review('app/controllers/posts_controller.rb', content)
expect(runner.errors.size).to eq(1)
expect(runner.errors[0].to_s).to eq('app/controllers/posts_controller.rb:5 - use scope access')
end
it 'uses scope access with current_user ==' do
content = <<-EOF
class PostsController < ApplicationController
def edit
@post = Post.find(params[:id])
unless current_user == @post.user
flash[:warning] = 'Access Denied'
redirect_to posts_url
end
end
end
EOF
runner.review('app/controllers/posts_controller.rb', content)
expect(runner.errors.size).to eq(1)
expect(runner.errors[0].to_s).to eq('app/controllers/posts_controller.rb:5 - use scope access')
end
it 'uses scope access by current_user.id ==' do
content = <<-EOF
class PostsController < ApplicationController
def edit
@post = Post.find(params[:id])
unless current_user.id == @post.user_id
flash[:warning] = 'Access Denied'
redirect_to posts_url
end
end
end
EOF
runner.review('app/controllers/posts_controller.rb', content)
expect(runner.errors.size).to eq(1)
expect(runner.errors[0].to_s).to eq('app/controllers/posts_controller.rb:5 - use scope access')
end
it 'noes error in use_scope_access_review' do
content = <<-EOF
class CommentsController < ApplicationController
def add_comment
@current_user = User.find_by_id(session[:user_id])
@id = params[:post_id]
@error = ""
if (@text = params[:text]) == ""
@error = "Please enter a comment!"
else
@comment = Comment.create_object(@text, @id, @current_user.id)
end
unless @comment
@error = "Comment could not be saved."
end
end
end
EOF
runner.review('app/controllers/comments_controller.rb', content)
expect(runner.errors.size).to eq(0)
end
it 'does not check ignored files' do
runner = Core::Runner.new(reviews: described_class.new(ignored_files: /posts_controller/))
content = <<-EOF
class PostsController < ApplicationController
def edit
@post = Post.find(params[:id])
unless @post.user == current_user
flash[:warning] = 'Access Denied'
redirect_to posts_url
end
end
end
EOF
runner.review('app/controllers/posts_controller.rb', content)
expect(runner.errors.size).to eq(0)
end
end
end
end
end
| ruby | MIT | 2ef40880d12ff8ed5f516871133ec569df03b192 | 2026-01-04T15:47:01.660067Z | false |
flyerhzm/rails_best_practices | https://github.com/flyerhzm/rails_best_practices/blob/2ef40880d12ff8ed5f516871133ec569df03b192/spec/rails_best_practices/reviews/use_before_filter_review_spec.rb | spec/rails_best_practices/reviews/use_before_filter_review_spec.rb | # frozen_string_literal: true
require 'spec_helper'
module RailsBestPractices
module Reviews
describe UseBeforeFilterReview do
let(:runner) { Core::Runner.new(reviews: described_class.new(customize_count: 2)) }
it 'uses before_filter' do
content = <<-EOF
class PostsController < ApplicationController
def show
@post = current_user.posts.find(params[:id])
end
def edit
@post = current_user.posts.find(params[:id])
end
def update
@post = current_user.posts.find(params[:id])
@post.update_attributes(params[:post])
end
def destroy
@post = current_user.posts.find(params[:id])
@post.destroy
end
end
EOF
runner.review('app/controllers/posts_controller.rb', content)
expect(runner.errors.size).to eq(1)
expect(runner.errors[0].to_s).to eq(
'app/controllers/posts_controller.rb:2,6,10,15 - use before_filter for show,edit,update,destroy'
)
end
it 'does not use before_filter when equal to customize count' do
content = <<-EOF
class PostsController < ApplicationController
def show
@post = Post.find(params[:id])
end
def edit
@post = Post.find(params[:id])
end
end
EOF
runner.review('app/controllers/posts_controller.rb', content)
expect(runner.errors.size).to eq(0)
end
it 'does not use before_filter' do
content = <<-EOF
class PostsController < ApplicationController
before_filter :find_post, only: [:show, :edit, :update, :destroy]
def update
@post.update_attributes(params[:post])
end
def destroy
@post.destroy
end
protected
def find_post
@post = current_user.posts.find(params[:id])
end
end
EOF
runner.review('app/controllers/posts_controller.rb', content)
expect(runner.errors.size).to eq(0)
end
it 'does not use before_filter by nil' do
content = <<-EOF
class PostsController < ApplicationController
def show; end
def edit; end
def update; end
def destroy; end
end
EOF
runner.review('app/controllers/posts_controller.rb', content)
expect(runner.errors.size).to eq(0)
end
it 'does not use before_filter for protected/private methods' do
content = <<-EOF
class PostsController < ApplicationController
protected
def load_comments
load_post
@comments = @post.comments
end
def load_user
load_post
@user = @post.user
end
end
EOF
runner.review('app/controllers/posts_controller.rb', content)
expect(runner.errors.size).to eq(0)
end
it 'does not check ignored files' do
runner = Core::Runner.new(reviews: described_class.new(customize_count: 2, ignored_files: /posts_controller/))
content = <<-EOF
class PostsController < ApplicationController
def show
@post = current_user.posts.find(params[:id])
end
def edit
@post = current_user.posts.find(params[:id])
end
def update
@post = current_user.posts.find(params[:id])
@post.update_attributes(params[:post])
end
def destroy
@post = current_user.posts.find(params[:id])
@post.destroy
end
end
EOF
runner.review('app/controllers/posts_controller.rb', content)
expect(runner.errors.size).to eq(1)
end
end
end
end
| ruby | MIT | 2ef40880d12ff8ed5f516871133ec569df03b192 | 2026-01-04T15:47:01.660067Z | false |
flyerhzm/rails_best_practices | https://github.com/flyerhzm/rails_best_practices/blob/2ef40880d12ff8ed5f516871133ec569df03b192/spec/rails_best_practices/reviews/use_query_attribute_review_spec.rb | spec/rails_best_practices/reviews/use_query_attribute_review_spec.rb | # frozen_string_literal: true
require 'spec_helper'
module RailsBestPractices
module Reviews
describe UseQueryAttributeReview do
let(:runner) do
Core::Runner.new(
prepares: [Prepares::ModelPrepare.new, Prepares::SchemaPrepare.new], reviews: described_class.new
)
end
before do
content = <<-EOF
class User < ActiveRecord::Base
has_many :projects
belongs_to :location
has_one :phone
belongs_to :category, class_name: 'IssueCategory', foreign_key: 'category_id'
end
EOF
runner.prepare('app/models/user.rb', content)
content = <<-EOF
ActiveRecord::Schema.define(version: 20110216150853) do
create_table "users", force => true do |t|
t.string :login
t.integer :age
end
end
EOF
runner.prepare('db/schema.rb', content)
end
it 'uses query attribute by blank call' do
content = <<-EOF
<% if @user.login.blank? %>
<%= link_to 'login', new_session_path %>
<% end %>
EOF
runner.review('app/views/users/show.html.erb', content)
expect(runner.errors.size).to eq(1)
expect(runner.errors[0].to_s).to eq('app/views/users/show.html.erb:1 - use query attribute (@user.login?)')
end
it 'uses query attribute by blank call with if in one line' do
content = <<-EOF
<%= link_to 'login', new_session_path if @user.login.blank? %>
EOF
runner.review('app/views/users/show.html.erb', content)
expect(runner.errors.size).to eq(1)
expect(runner.errors[0].to_s).to eq('app/views/users/show.html.erb:1 - use query attribute (@user.login?)')
end
it "uses query attribute by blank call with '? :'" do
content = <<-EOF
<%= @user.login.blank? ? link_to('login', new_session_path) : '' %>
EOF
runner.review('app/views/users/show.html.erb', content)
expect(runner.errors.size).to eq(1)
expect(runner.errors[0].to_s).to eq('app/views/users/show.html.erb:1 - use query attribute (@user.login?)')
end
it 'uses query attribute by comparing empty string' do
content = <<-EOF
<% if @user.login == "" %>
<%= link_to 'login', new_session_path %>
<% end %>
EOF
runner.review('app/views/users/show.html.erb', content)
expect(runner.errors.size).to eq(1)
expect(runner.errors[0].to_s).to eq('app/views/users/show.html.erb:1 - use query attribute (@user.login?)')
end
it 'uses query attribute by nil call' do
content = <<-EOF
<% if @user.login.nil? %>
<%= link_to 'login', new_session_path %>
<% end %>
EOF
runner.review('app/views/users/show.html.erb', content)
expect(runner.errors.size).to eq(1)
expect(runner.errors[0].to_s).to eq('app/views/users/show.html.erb:1 - use query attribute (@user.login?)')
end
it 'uses query attribute by present call' do
content = <<-EOF
<% if @user.login.present? %>
<%= @user.login %>
<% end %>
EOF
runner.review('app/views/users/show.html.erb', content)
expect(runner.errors.size).to eq(1)
expect(runner.errors[0].to_s).to eq('app/views/users/show.html.erb:1 - use query attribute (@user.login?)')
end
it 'uses query attribute within and conditions' do
content = <<-EOF
<% if @user.active? && @user.login.present? %>
<%= @user.login %>
<% end %>
EOF
runner.review('app/views/users/show.html.erb', content)
expect(runner.errors.size).to eq(1)
expect(runner.errors[0].to_s).to eq('app/views/users/show.html.erb:1 - use query attribute (@user.login?)')
end
it 'uses query attribute within or conditions' do
content = <<-EOF
<% if @user.active? or @user.login != "" %>
<%= @user.login %>
<% end %>
EOF
runner.review('app/views/users/show.html.erb', content)
expect(runner.errors.size).to eq(1)
expect(runner.errors[0].to_s).to eq('app/views/users/show.html.erb:1 - use query attribute (@user.login?)')
end
it 'does not use query attribute' do
content = <<-EOF
<% if @user.login? %>
<%= @user.login %>
<% end %>
EOF
runner.review('app/views/users/show.html.erb', content)
expect(runner.errors.size).to eq(0)
end
it 'does not use query attribute for number' do
content = <<-EOF
<% unless @user.age.blank? %>
<%= @user.age %>
<% end %>
EOF
runner.review('app/views/users/show.html.erb', content)
expect(runner.errors.size).to eq(0)
end
it 'does not review for pluralize attribute' do
content = <<-EOF
<% if @user.roles.blank? %>
<%= @user.login %>
<% end %>
EOF
runner.review('app/views/users/show.html.erb', content)
expect(runner.errors.size).to eq(0)
end
it 'does not review non model class' do
content = <<-EOF
<% if @person.login.present? %>
<%= @person.login %>
<% end %>
EOF
runner.review('app/views/users/show.html.erb', content)
expect(runner.errors.size).to eq(0)
end
context 'association' do
it 'does not review belongs_to association' do
content = <<-EOF
<% if @user.location.present? %>
<%= @user.location.name %>
<% end %>
EOF
runner.review('app/views/users/show.html.erb', content)
expect(runner.errors.size).to eq(0)
end
it 'does not review belongs_to category' do
content = <<-EOF
<% if @user.category.present? %>
<%= @user.category.name %>
<% end %>
EOF
runner.review('app/views/users/show.html.erb', content)
expect(runner.errors.size).to eq(0)
end
it 'does not review has_one association' do
content = <<-EOF
<% if @user.phone.present? %>
<%= @user.phone.number %>
<% end %>
EOF
runner.review('app/views/users/show.html.erb', content)
expect(runner.errors.size).to eq(0)
end
it 'does not review has_many association' do
content = <<-EOF
<% if @user.projects.present? %>
<%= @user.projects.first.name %>
<% end %>
EOF
runner.review('app/views/users/show.html.erb', content)
expect(runner.errors.size).to eq(0)
end
end
it 'does not review for class method' do
content = <<-EOF
<% if User.name.present? %>
<%= User.name %>
<% end %>
EOF
runner.review('app/views/users/show.html.erb', content)
expect(runner.errors.size).to eq(0)
end
it 'does not review for non attribute call' do
content = <<-EOF
if @user.login(false).nil?
puts @user.login(false)
end
EOF
runner.review('app/models/users_controller.rb', content)
expect(runner.errors.size).to eq(0)
end
it 'does not raise error for common conditional statement' do
content = <<-EOF
if voteable.is_a? Answer
puts voteable.title
end
EOF
expect { runner.review('app/models/users_controller.rb', content) }.not_to raise_error
end
it 'does not check ignored files' do
runner =
Core::Runner.new(
prepares: [Prepares::ModelPrepare.new, Prepares::SchemaPrepare.new],
reviews: described_class.new(ignored_files: %r{users/show})
)
content = <<-EOF
<% if @user.login.blank? %>
<%= link_to 'login', new_session_path %>
<% end %>
EOF
runner.review('app/views/users/show.html.erb', content)
expect(runner.errors.size).to eq(0)
end
end
end
end
| ruby | MIT | 2ef40880d12ff8ed5f516871133ec569df03b192 | 2026-01-04T15:47:01.660067Z | false |
flyerhzm/rails_best_practices | https://github.com/flyerhzm/rails_best_practices/blob/2ef40880d12ff8ed5f516871133ec569df03b192/spec/rails_best_practices/reviews/remove_unused_methods_in_helpers_review_spec.rb | spec/rails_best_practices/reviews/remove_unused_methods_in_helpers_review_spec.rb | # frozen_string_literal: true
require 'spec_helper'
module RailsBestPractices
module Reviews
describe RemoveUnusedMethodsInHelpersReview do
let(:runner) do
Core::Runner.new(
prepares: [Prepares::ControllerPrepare.new, Prepares::HelperPrepare.new],
reviews: described_class.new(except_methods: [])
)
end
it 'removes unused methods' do
content = <<-EOF
module PostsHelper
def unused; end
end
EOF
runner.prepare('app/helpers/posts_helper.rb', content)
runner.review('app/helpers/posts_helper.rb', content)
runner.after_review
expect(runner.errors.size).to eq(1)
expect(runner.errors[0].to_s).to eq(
'app/helpers/posts_helper.rb:2 - remove unused methods (PostsHelper#unused)'
)
end
it 'does not remove unused methods if called on views' do
content = <<-EOF
module PostsHelper
def used?(post); end
end
EOF
runner.prepare('app/helpers/posts_helper.rb', content)
runner.review('app/helpers/posts_helper.rb', content)
content = <<-EOF
<% if used?(@post) %>
<% end %>
EOF
runner.review('app/views/posts/show.html.erb', content)
runner.after_review
expect(runner.errors.size).to eq(0)
end
it 'does not remove unused methods if called on helpers' do
content = <<-EOF
module PostsHelper
def used?(post)
test?(post)
end
def test?(post); end
end
EOF
runner.prepare('app/helpers/posts_helper.rb', content)
runner.review('app/helpers/posts_helper.rb', content)
content = <<-EOF
<% if used?(@post) %>
<% end %>
EOF
runner.review('app/views/posts/show.html.erb', content)
runner.after_review
expect(runner.errors.size).to eq(0)
end
it 'does not remove unused methods if called on controllers' do
helper_content = <<-EOF
module PostsHelper
def used?(post); end
end
EOF
controller_content = <<-EOF
class PostsController < InheritedResources::Base
include PostsHelper
def show
@post = Post.find(params[:id])
used?(@post)
end
end
EOF
runner.prepare('app/helpers/posts_helper.rb', helper_content)
runner.prepare('app/controllers/posts_controller.rb', controller_content)
runner.after_prepare
runner.review('app/helpers/posts_helper.rb', helper_content)
runner.review('app/controllers/posts_controller.rb', controller_content)
runner.after_review
expect(runner.errors.size).to eq(0)
end
it 'does not remove unused methods if called in descendant controllers' do
application_helper_content = <<-EOF
module ApplicationHelper
def admin?; end
end
EOF
application_controller_content = <<-EOF
class ApplicationController
include ApplicationHelper
end
EOF
controller_content = <<-EOF
class PostsController < ApplicationController
def show
head(:forbidden) unless admin?
end
end
EOF
runner.prepare('app/helpers/application_helper.rb', application_helper_content)
runner.prepare('app/controllers/application_controller.rb', application_controller_content)
runner.prepare('app/controllers/posts_controller.rb', controller_content)
runner.after_prepare
runner.review('app/helpers/application_helper.rb', application_helper_content)
runner.review('app/controllers/application_controller.rb', application_controller_content)
runner.review('app/controllers/posts_controller.rb', controller_content)
runner.after_review
expect(runner.errors.size).to eq(0)
end
it 'does not check ignored files' do
runner =
Core::Runner.new(
prepares: [Prepares::ControllerPrepare.new, Prepares::HelperPrepare.new],
reviews: described_class.new(ignored_files: /posts_helper/, except_methods: [])
)
content = <<-EOF
module PostsHelper
def unused; end
end
EOF
runner.prepare('app/helpers/posts_helper.rb', content)
runner.review('app/helpers/posts_helper.rb', content)
runner.after_review
expect(runner.errors.size).to eq(0)
end
end
end
end
| ruby | MIT | 2ef40880d12ff8ed5f516871133ec569df03b192 | 2026-01-04T15:47:01.660067Z | false |
flyerhzm/rails_best_practices | https://github.com/flyerhzm/rails_best_practices/blob/2ef40880d12ff8ed5f516871133ec569df03b192/spec/rails_best_practices/reviews/protect_mass_assignment_review_spec.rb | spec/rails_best_practices/reviews/protect_mass_assignment_review_spec.rb | # frozen_string_literal: true
require 'spec_helper'
module RailsBestPractices
module Reviews
describe ProtectMassAssignmentReview do
let(:runner) do
Core::Runner.new(
prepares: [Prepares::GemfilePrepare.new, Prepares::ConfigPrepare.new, Prepares::InitializerPrepare.new],
reviews: described_class.new
)
end
it 'protects mass assignment' do
content = <<-EOF
class User < ActiveRecord::Base
end
EOF
runner.review('app/models/user.rb', content)
expect(runner.errors.size).to eq(1)
expect(runner.errors[0].to_s).to eq('app/models/user.rb:1 - protect mass assignment')
end
it 'does not protect mass assignment if attr_accessible is used with arguments and user set config.active_record.whitelist_attributes' do
content = <<-EOF
module RailsBestPracticesCom
class Application < Rails::Application
config.active_record.whitelist_attributes = true
end
end
EOF
runner.prepare('config/application.rb', content)
content = <<-EOF
class User < ActiveRecord::Base
attr_accessible :email, :password, :password_confirmation
end
EOF
runner.review('app/models/user.rb', content)
expect(runner.errors.size).to eq(0)
end
it 'does not protect mass assignment if attr_accessible is used without arguments and user set config.active_record.whitelist_attributes' do
content = <<-EOF
module RailsBestPracticesCom
class Application < Rails::Application
config.active_record.whitelist_attributes = true
end
end
EOF
runner.prepare('config/application.rb', content)
content = <<-EOF
class User < ActiveRecord::Base
attr_accessible
end
EOF
runner.review('app/models/user.rb', content)
expect(runner.errors.size).to eq(0)
end
it 'does not protect mass assignment with attr_protected if user set config.active_record.whitelist_attributes' do
content = <<-EOF
module RailsBestPracticesCom
class Application < Rails::Application
config.active_record.whitelist_attributes = true
end
end
EOF
runner.prepare('config/application.rb', content)
content = <<-EOF
class User < ActiveRecord::Base
attr_protected :role
end
EOF
runner.review('app/models/user.rb', content)
expect(runner.errors.size).to eq(0)
end
it 'does not protect mass assignment if using devise' do
content = <<-EOF
class User < ActiveRecord::Base
devise :database_authenticatable, :registerable, :confirmable, :recoverable, stretches: 20
end
EOF
runner.review('app/models/user.rb', content)
expect(runner.errors.size).to eq(0)
end
it 'does not protect mass assignment if using authlogic with configuration' do
content = <<-EOF
class User < ActiveRecord::Base
acts_as_authentic do |c|
c.my_config_option = my_value
end
end
EOF
runner.review('app/models/user.rb', content)
expect(runner.errors.size).to eq(0)
end
it 'does not protect mass assignment if using authlogic without configuration' do
content = <<-EOF
class User < ActiveRecord::Base
acts_as_authentic
end
EOF
runner.review('app/models/user.rb', content)
expect(runner.errors.size).to eq(0)
end
it 'does not protect mass assignment if checking non ActiveRecord::Base inherited model' do
content = <<-EOF
class User < Person
end
EOF
runner.review('app/models/user.rb', content)
expect(runner.errors.size).to eq(0)
end
context 'strong_parameters' do
it 'does not protect mass assignment for strong_parameters' do
content = <<-EOF
class User < ActiveRecord::Base
include ActiveModel::ForbiddenAttributesProtection
end
EOF
runner.review('app/models/user.rb', content)
expect(runner.errors.size).to eq(0)
end
it 'does not protect mass assignment for strong_parameters' do
content = <<-EOF
class AR
ActiveRecord::Base.send(:include, ActiveModel::ForbiddenAttributesProtection)
end
EOF
runner.prepare('config/initializers/ar.rb', content)
content = <<-EOF
class User < ActiveRecord::Base
end
EOF
runner.review('app/models/user.rb', content)
expect(runner.errors.size).to eq(0)
end
end
context 'activerecord 4' do
it 'does not protect mass assignment for activerecord 4' do
content = <<-EOF
GEM
remote: https://rubygems.org
specs:
activerecord (4.0.0)
EOF
runner.prepare('Gemfile.lock', content)
content = <<-EOF
class User < ActiveRecord::Base
end
EOF
runner.review('app/models/user.rb', content)
expect(runner.errors.size).to eq(0)
end
it 'protects mass assignment for activerecord 3' do
content = <<-EOF
GEM
remote: https://rubygems.org
specs:
activerecord (3.2.13)
EOF
runner.prepare('Gemfile.lock', content)
content = <<-EOF
class User < ActiveRecord::Base
end
EOF
runner.review('app/models/user.rb', content)
expect(runner.errors.size).to eq(1)
end
end
it 'does not check ignored files' do
runner =
Core::Runner.new(
prepares: [Prepares::GemfilePrepare.new, Prepares::ConfigPrepare.new, Prepares::InitializerPrepare.new],
reviews: described_class.new(ignored_files: %r{app/models/user\.rb})
)
content = <<-EOF
class User < ActiveRecord::Base
end
EOF
runner.review('app/models/user.rb', content)
expect(runner.errors.size).to eq(0)
end
end
end
end
| ruby | MIT | 2ef40880d12ff8ed5f516871133ec569df03b192 | 2026-01-04T15:47:01.660067Z | false |
flyerhzm/rails_best_practices | https://github.com/flyerhzm/rails_best_practices/blob/2ef40880d12ff8ed5f516871133ec569df03b192/spec/rails_best_practices/reviews/not_use_time_ago_in_words_review_spec.rb | spec/rails_best_practices/reviews/not_use_time_ago_in_words_review_spec.rb | # frozen_string_literal: true
require 'spec_helper'
module RailsBestPractices
module Reviews
describe NotUseTimeAgoInWordsReview do
let(:runner) { Core::Runner.new(reviews: described_class.new) }
describe 'time_ago_in_words' do
it 'does not use in views' do
content = <<-EOF
<%= time_ago_in_words(post.created_at) %>
EOF
runner.review('app/views/posts/show.html.erb', content)
expect(runner.errors.size).to eq(1)
expect(runner.errors[0].to_s).to eq('app/views/posts/show.html.erb:1 - not use time_ago_in_words')
end
it 'does not use in helpers' do
content = <<-EOF
def timeago
content_tag(:p, time_ago_in_words(post.created_at))
end
EOF
runner.review('app/helpers/posts_helper.rb', content)
expect(runner.errors.size).to eq(1)
expect(runner.errors[0].to_s).to eq('app/helpers/posts_helper.rb:2 - not use time_ago_in_words')
end
end
describe 'distance_of_time_in_words_to_now' do
it 'does not use in views' do
content = <<-EOF
<%= distance_of_time_in_words_to_now(post.created_at) %>
EOF
runner.review('app/views/posts/show.html.erb', content)
expect(runner.errors.size).to eq(1)
expect(runner.errors[0].to_s).to eq('app/views/posts/show.html.erb:1 - not use time_ago_in_words')
end
it 'does not use in helpers' do
content = <<-EOF
def timeago
content_tag(:p, distance_of_time_in_words_to_now(post.created_at))
end
EOF
runner.review('app/helpers/posts_helper.rb', content)
expect(runner.errors.size).to eq(1)
expect(runner.errors[0].to_s).to eq('app/helpers/posts_helper.rb:2 - not use time_ago_in_words')
end
end
it 'does not check ignored files' do
runner = Core::Runner.new(reviews: described_class.new(ignored_files: /posts_helper/))
content = <<-EOF
def timeago
content_tag(:p, time_ago_in_words(post.created_at))
end
EOF
runner.review('app/helpers/posts_helper.rb', content)
expect(runner.errors.size).to eq(0)
end
end
end
end
| ruby | MIT | 2ef40880d12ff8ed5f516871133ec569df03b192 | 2026-01-04T15:47:01.660067Z | false |
flyerhzm/rails_best_practices | https://github.com/flyerhzm/rails_best_practices/blob/2ef40880d12ff8ed5f516871133ec569df03b192/spec/rails_best_practices/reviews/needless_deep_nesting_review_spec.rb | spec/rails_best_practices/reviews/needless_deep_nesting_review_spec.rb | # frozen_string_literal: true
require 'spec_helper'
module RailsBestPractices
module Reviews
describe NeedlessDeepNestingReview do
let(:runner) { Core::Runner.new(reviews: described_class.new) }
it 'needlesses deep nesting' do
content = <<-EOF
resources :posts do
resources :comments do
resources :favorites
end
end
EOF
runner.review('config/routes.rb', content)
expect(runner.errors.size).to eq(1)
expect(runner.errors[0].to_s).to eq('config/routes.rb:3 - needless deep nesting (nested_count > 2)')
end
it 'does not needless deep nesting for shallow' do
content = <<-EOF
resources :posts, shallow: true do
resources :comments do
resources :favorites
end
end
EOF
runner.review('config/routes.rb', content)
expect(runner.errors.size).to eq(0)
end
it 'does not needless deep nesting for shallow 4 levels' do
content = <<-EOF
resources :applications, shallow: true, only: [:index, :show, :create] do
resources :events, only: [:index, :show, :create, :subscribe, :push] do
resources :executions, only: [:index, :show] do
resources :execution_statuses, only: :index
end
end
end
EOF
runner.review('config/routes.rb', content)
expect(runner.errors.size).to eq(0)
end
it 'needlesses deep nesting with resource' do
content = <<-EOF
resources :posts do
resources :comments do
resource :vote
end
end
EOF
runner.review('config/routes.rb', content)
expect(runner.errors.size).to eq(1)
expect(runner.errors[0].to_s).to eq('config/routes.rb:3 - needless deep nesting (nested_count > 2)')
end
it 'needlesses deep nesting with block node' do
content = <<-EOF
resources :posts do
resources :comments do
resources :favorites
end
resources :votes
end
EOF
runner.review('config/routes.rb', content)
expect(runner.errors.size).to eq(1)
expect(runner.errors[0].to_s).to eq('config/routes.rb:3 - needless deep nesting (nested_count > 2)')
end
it 'noes needless deep nesting' do
content = <<-EOF
resources :posts do
resources :comments
resources :votes
end
resources :comments do
resources :favorites
end
EOF
runner.review('config/routes.rb', content)
expect(runner.errors.size).to eq(0)
end
it 'does not check ignored files' do
runner = Core::Runner.new(reviews: described_class.new(ignored_files: %r{config/routes}))
content = <<-EOF
map.resources :posts do |post|
post.resources :comments do |comment|
comment.resources :favorites
end
end
EOF
runner.review('config/routes.rb', content)
expect(runner.errors.size).to eq(0)
end
end
end
end
| ruby | MIT | 2ef40880d12ff8ed5f516871133ec569df03b192 | 2026-01-04T15:47:01.660067Z | false |
flyerhzm/rails_best_practices | https://github.com/flyerhzm/rails_best_practices/blob/2ef40880d12ff8ed5f516871133ec569df03b192/spec/rails_best_practices/reviews/law_of_demeter_review_spec.rb | spec/rails_best_practices/reviews/law_of_demeter_review_spec.rb | # frozen_string_literal: true
require 'spec_helper'
module RailsBestPractices
module Reviews
describe LawOfDemeterReview do
let(:runner) do
Core::Runner.new(
prepares: [Prepares::ModelPrepare.new, Prepares::SchemaPrepare.new], reviews: described_class.new
)
end
describe 'belongs_to' do
before do
content = <<-EOF
class Invoice < ActiveRecord::Base
belongs_to :user
end
EOF
runner.prepare('app/models/invoice.rb', content)
content = <<-EOF
ActiveRecord::Schema.define(version: 20110216150853) do
create_table "users", force => true do |t|
t.string :name
t.string :address
t.string :cellphone
end
end
EOF
runner.prepare('db/schema.rb', content)
end
it 'laws of demeter with erb' do
content = <<-EOF
<%= @invoice.user.name %>
<%= @invoice.user.address %>
<%= @invoice.user.cellphone %>
EOF
runner.review('app/views/invoices/show.html.erb', content)
expect(runner.errors.size).to eq(3)
expect(runner.errors[0].to_s).to eq('app/views/invoices/show.html.erb:1 - law of demeter')
end
it 'laws of demeter with haml' do
content = <<~EOF
= @invoice.user.name
= @invoice.user.address
= @invoice.user.cellphone
EOF
runner.review('app/views/invoices/show.html.haml', content)
expect(runner.errors.size).to eq(3)
expect(runner.errors[0].to_s).to eq('app/views/invoices/show.html.haml:1 - law of demeter')
end
it 'laws of demeter with slim' do
content = <<~EOF
= @invoice.user.name
= @invoice.user.address
= @invoice.user.cellphone
EOF
runner.review('app/views/invoices/show.html.slim', content)
expect(runner.errors.size).to eq(3)
expect(runner.errors[0].to_s).to eq('app/views/invoices/show.html.slim:1 - law of demeter')
end
it 'noes law of demeter' do
content = <<-EOF
<%= @invoice.user_name %>
<%= @invoice.user_address %>
<%= @invoice.user_cellphone %>
EOF
runner.review('app/views/invoices/show.html.erb', content)
expect(runner.errors.size).to eq(0)
end
end
describe 'has_one' do
before do
content = <<-EOF
class Invoice < ActiveRecord::Base
has_one :price
end
EOF
runner.prepare('app/models/invoice.rb', content)
content = <<-EOF
ActiveRecord::Schema.define(version: 20110216150853) do
create_table "prices", force => true do |t|
t.string :currency
t.integer :number
end
end
EOF
runner.prepare('db/schema.rb', content)
end
it 'laws of demeter' do
content = <<-EOF
<%= @invoice.price.currency %>
<%= @invoice.price.number %>
EOF
runner.review('app/views/invoices/show.html.erb', content)
expect(runner.errors.size).to eq(2)
expect(runner.errors[0].to_s).to eq('app/views/invoices/show.html.erb:1 - law of demeter')
end
end
context 'polymorphic association' do
before do
content = <<-EOF
class Comment < ActiveRecord::Base
belongs_to :commentable, polymorphic: true
end
EOF
runner.prepare('app/models/comment.rb', content)
content = <<-EOF
class Post < ActiveRecord::Base
has_many :comments
end
EOF
runner.prepare('app/models/comment.rb', content)
content = <<-EOF
ActiveRecord::Schema.define(version: 20110216150853) do
create_table "posts", force => true do |t|
t.string :title
end
end
EOF
runner.prepare('db/schema.rb', content)
end
it 'laws of demeter' do
content = <<-EOF
<%= @comment.commentable.title %>
EOF
runner.review('app/views/comments/index.html.erb', content)
expect(runner.errors.size).to eq(1)
expect(runner.errors[0].to_s).to eq('app/views/comments/index.html.erb:1 - law of demeter')
end
end
it 'noes law of demeter with method call' do
content = <<-EOF
class Question < ActiveRecord::Base
has_many :answers, dependent: :destroy
end
EOF
runner.prepare('app/models/question.rb', content)
content = <<-EOF
class Answer < ActiveRecord::Base
belongs_to :question, counter_cache: true, touch: true
end
EOF
runner.prepare('app/models/answer.rb', content)
content = <<-EOF
class CommentsController < ApplicationController
def comment_url
question_path(@answer.question)
end
end
EOF
runner.review('app/controllers/comments_controller.rb', content)
expect(runner.errors.size).to eq(0)
end
it 'does not check ignored files' do
runner =
Core::Runner.new(
prepares: [Prepares::ModelPrepare.new, Prepares::SchemaPrepare.new],
reviews: described_class.new(ignored_files: %r{app/views/invoices})
)
content = <<-EOF
<%= @invoice.user.name %>
<%= @invoice.user.address %>
<%= @invoice.user.cellphone %>
EOF
runner.review('app/views/invoices/show.html.erb', content)
expect(runner.errors.size).to eq(0)
end
end
end
end
| ruby | MIT | 2ef40880d12ff8ed5f516871133ec569df03b192 | 2026-01-04T15:47:01.660067Z | false |
flyerhzm/rails_best_practices | https://github.com/flyerhzm/rails_best_practices/blob/2ef40880d12ff8ed5f516871133ec569df03b192/spec/rails_best_practices/reviews/simplify_render_in_views_review_spec.rb | spec/rails_best_practices/reviews/simplify_render_in_views_review_spec.rb | # frozen_string_literal: true
require 'spec_helper'
module RailsBestPractices
module Reviews
describe SimplifyRenderInViewsReview do
let(:runner) { Core::Runner.new(reviews: described_class.new) }
it 'simplifies render simple partial' do
content = <<-EOF
<%= render partial: 'sidebar' %>
EOF
runner.review('app/views/posts/index.html.erb', content)
expect(runner.errors.size).to eq(1)
expect(runner.errors[0].to_s).to eq('app/views/posts/index.html.erb:1 - simplify render in views')
end
it 'simplifies render partial with object' do
content = <<-EOF
<%= render partial: 'post', object: @post %>
EOF
runner.review('app/views/posts/index.html.erb', content)
expect(runner.errors.size).to eq(1)
expect(runner.errors[0].to_s).to eq('app/views/posts/index.html.erb:1 - simplify render in views')
end
it 'simplifies render partial with collection' do
content = <<-EOF
<%= render partial: 'posts', collection: @posts %>
EOF
runner.review('app/views/posts/index.html.erb', content)
expect(runner.errors.size).to eq(1)
expect(runner.errors[0].to_s).to eq('app/views/posts/index.html.erb:1 - simplify render in views')
end
it 'simplifies render partial with local variables' do
content = <<-EOF
<%= render partial: 'comment', locals: { parent: post } %>
EOF
runner.review('app/views/posts/index.html.erb', content)
expect(runner.errors.size).to eq(1)
expect(runner.errors[0].to_s).to eq('app/views/posts/index.html.erb:1 - simplify render in views')
end
it 'does not simplify render simple partial' do
content = <<-EOF
<%= render 'sidebar' %>
<%= render 'shared/sidebar' %>
EOF
runner.review('app/views/posts/index.html.erb', content)
expect(runner.errors.size).to eq(0)
end
it 'does not simplify render partial with object' do
content = <<-EOF
<%= render @post %>
EOF
runner.review('app/views/posts/index.html.erb', content)
expect(runner.errors.size).to eq(0)
end
it 'does not simplify render partial with collection' do
content = <<-EOF
<%= render @posts %>
EOF
runner.review('app/views/posts/index.html.erb', content)
expect(runner.errors.size).to eq(0)
end
it 'does not simplify render partial with local variables' do
content = <<-EOF
<%= render 'comment', parent: post %>
EOF
runner.review('app/views/posts/index.html.erb', content)
expect(runner.errors.size).to eq(0)
end
it 'does not simplify render partial with complex partial' do
content = <<-EOF
<%= render partial: 'shared/post', object: @post %>
EOF
runner.review('app/views/posts/index.html.erb', content)
expect(runner.errors.size).to eq(0)
end
it 'does not simplify render partial with layout option' do
content = <<-EOF
<%= render partial: 'post', layout: 'post' %>
EOF
runner.review('app/views/posts/index.html.erb', content)
expect(runner.errors.size).to eq(0)
end
it 'does not check ignored files' do
runner = Core::Runner.new(reviews: described_class.new(ignored_files: %r{views/posts/index}))
content = <<-EOF
<%= render partial: 'sidebar' %>
EOF
runner.review('app/views/posts/index.html.erb', content)
expect(runner.errors.size).to eq(0)
end
end
end
end
| ruby | MIT | 2ef40880d12ff8ed5f516871133ec569df03b192 | 2026-01-04T15:47:01.660067Z | false |
flyerhzm/rails_best_practices | https://github.com/flyerhzm/rails_best_practices/blob/2ef40880d12ff8ed5f516871133ec569df03b192/spec/rails_best_practices/reviews/not_rescue_exception_review_spec.rb | spec/rails_best_practices/reviews/not_rescue_exception_review_spec.rb | # frozen_string_literal: true
require 'spec_helper'
module RailsBestPractices
module Reviews
describe NotRescueExceptionReview do
let(:runner) { Core::Runner.new(reviews: described_class.new) }
describe 'not_rescue_exception' do
it 'does not rescue exception in method rescue with named var' do
content = <<-EOF
def my_method
do_something
rescue Exception => e
logger.error e
end
EOF
runner.review('app/helpers/posts_helper.rb', content)
expect(runner.errors.size).to eq(1)
expect(runner.errors[0].to_s).to eq("app/helpers/posts_helper.rb:3 - Don't rescue Exception")
end
it 'does not rescue exception in method rescue without named var' do
content = <<-EOF
def my_method
do_something
rescue Exception
logger.error $!
end
EOF
runner.review('app/helpers/posts_helper.rb', content)
expect(runner.errors.size).to eq(1)
expect(runner.errors[0].to_s).to eq("app/helpers/posts_helper.rb:3 - Don't rescue Exception")
end
it 'does not rescue exception in block rescue with named var' do
content = <<-EOF
def my_method
begin
do_something
rescue Exception => e
logger.error e
end
end
EOF
runner.review('app/helpers/posts_helper.rb', content)
expect(runner.errors.size).to eq(1)
expect(runner.errors[0].to_s).to eq("app/helpers/posts_helper.rb:4 - Don't rescue Exception")
end
it 'does not rescue exception in block rescue without named var' do
content = <<-EOF
def my_method
begin
do_something
rescue Exception
logger.error $!
end
end
EOF
runner.review('app/helpers/posts_helper.rb', content)
expect(runner.errors.size).to eq(1)
expect(runner.errors[0].to_s).to eq("app/helpers/posts_helper.rb:4 - Don't rescue Exception")
end
it 'allows rescue implicit StandardError in block rescue without named var' do
content = <<-EOF
def my_method
begin
do_something
rescue
logger.error $!
end
end
EOF
runner.review('app/helpers/posts_helper.rb', content)
expect(runner.errors.size).to eq(0)
end
it 'allows rescue explicit StandardError in block rescue without named var' do
content = <<-EOF
def my_method
begin
do_something
rescue StandardError
logger.error $!
end
end
EOF
runner.review('app/helpers/posts_helper.rb', content)
expect(runner.errors.size).to eq(0)
end
it 'does not check ignored files' do
runner = Core::Runner.new(reviews: described_class.new(ignored_files: /posts_helper/))
content = <<-EOF
def my_method
do_something
rescue Exception => e
logger.error e
end
EOF
runner.review('app/helpers/posts_helper.rb', content)
expect(runner.errors.size).to eq(0)
end
end
end
end
end
| ruby | MIT | 2ef40880d12ff8ed5f516871133ec569df03b192 | 2026-01-04T15:47:01.660067Z | false |
flyerhzm/rails_best_practices | https://github.com/flyerhzm/rails_best_practices/blob/2ef40880d12ff8ed5f516871133ec569df03b192/spec/rails_best_practices/reviews/use_model_association_review_spec.rb | spec/rails_best_practices/reviews/use_model_association_review_spec.rb | # frozen_string_literal: true
require 'spec_helper'
module RailsBestPractices
module Reviews
describe UseModelAssociationReview do
let(:runner) { Core::Runner.new(reviews: described_class.new) }
it 'uses model association for instance variable' do
content = <<-EOF
class PostsController < ApplicationController
def create
@post = Post.new(params[:post])
@post.user_id = current_user.id
@post.save
end
end
EOF
runner.review('app/controllers/posts_controller.rb', content)
expect(runner.errors.size).to eq(1)
expect(runner.errors[0].to_s).to eq('app/controllers/posts_controller.rb:2 - use model association (for @post)')
end
it 'does not use model association without association assign' do
content = <<-EOF
class PostsController < ApplicationController
def create
@post = Post.new(params[:post])
@post.save
end
end
EOF
runner.review('app/controllers/posts_controller.rb', content)
expect(runner.errors.size).to eq(0)
end
it 'uses model association for local variable' do
content = <<-EOF
class PostsController < ApplicationController
def create
post = Post.new(params[:post])
post.user_id = current_user.id
post.save
end
end
EOF
runner.review('app/controllers/posts_controller.rb', content)
expect(runner.errors.size).to eq(1)
expect(runner.errors[0].to_s).to eq('app/controllers/posts_controller.rb:2 - use model association (for post)')
end
it 'does not use model association' do
content = <<-EOF
class PostsController < ApplicationController
def create
post = current_user.posts.buid(params[:post])
post.save
end
end
EOF
runner.review('app/controllers/posts_controller.rb', content)
expect(runner.errors.size).to eq(0)
end
it 'does not check ignored files' do
runner = Core::Runner.new(reviews: described_class.new(ignored_files: /posts_controller/))
content = <<-EOF
class PostsController < ApplicationController
def create
@post = Post.new(params[:post])
@post.user_id = current_user.id
@post.save
end
end
EOF
runner.review('app/controllers/posts_controller.rb', content)
expect(runner.errors.size).to eq(0)
end
end
end
end
| ruby | MIT | 2ef40880d12ff8ed5f516871133ec569df03b192 | 2026-01-04T15:47:01.660067Z | false |
flyerhzm/rails_best_practices | https://github.com/flyerhzm/rails_best_practices/blob/2ef40880d12ff8ed5f516871133ec569df03b192/spec/rails_best_practices/core_ext/erubis_spec.rb | spec/rails_best_practices/core_ext/erubis_spec.rb | # frozen_string_literal: true
require 'spec_helper'
describe Erubis::OnlyRuby do
subject do
content = <<-EOF
<h1>Title</h1>
<% if current_user %>
<%= link_to 'account', edit_user_path(current_user) %>
<%= "Hello \#{current_user.email}" %>
<% else %>
Not logged in
<% end %>
EOF
described_class.new(content).src
end
it { is_expected.not_to include('h1') }
it { is_expected.not_to include('Title') }
it { is_expected.not_to include('Not logged in') }
it { is_expected.to include('current_user') }
it { is_expected.to include('if') }
it { is_expected.to include('else') }
it { is_expected.to include('end') }
end
| ruby | MIT | 2ef40880d12ff8ed5f516871133ec569df03b192 | 2026-01-04T15:47:01.660067Z | false |
flyerhzm/rails_best_practices | https://github.com/flyerhzm/rails_best_practices/blob/2ef40880d12ff8ed5f516871133ec569df03b192/spec/rails_best_practices/inline_disables/inline_disable_spec.rb | spec/rails_best_practices/inline_disables/inline_disable_spec.rb | # frozen_string_literal: true
require 'spec_helper'
module RailsBestPractices
module InlineDisables
describe InlineDisable do
let(:runner) { Core::Runner.new(reviews: Reviews::MoveModelLogicIntoModelReview.new) }
it 'moves model logic into model' do
content = <<-EOF
class PostsController < ApplicationController
def publish
@post = Post.find(params[:id])
@post.update_attributes(:is_published, true)
@post.approved_by = current_user
if @post.created_at > Time.now - 7.days
@post.popular = 100
else
@post.popular = 0
end
redirect_to post_url(@post)
end
end
EOF
runner.review('app/controllers/posts_controller.rb', content)
runner.inline_disable('app/controllers/posts_controller.rb', content)
expect(runner.errors.size).to eq(1)
expect(runner.errors[0].to_s).to eq(
'app/controllers/posts_controller.rb:2 - move model logic into model (@post use_count > 4)'
)
end
it 'is no error is output' do
content = <<-EOF
class PostsController < ApplicationController
def publish # rails_best_practices:disable MoveModelLogicIntoModelCheck
@post = Post.find(params[:id])
@post.update_attributes(:is_published, true)
@post.approved_by = current_user
if @post.created_at > Time.now - 7.days
@post.popular = 100
else
@post.popular = 0
end
redirect_to post_url(@post)
end
end
EOF
runner.review('app/controllers/posts_controller.rb', content)
runner.inline_disable('app/controllers/posts_controller.rb', content)
expect(runner.errors.size).to eq(0)
end
end
end
end
| ruby | MIT | 2ef40880d12ff8ed5f516871133ec569df03b192 | 2026-01-04T15:47:01.660067Z | false |
flyerhzm/rails_best_practices | https://github.com/flyerhzm/rails_best_practices/blob/2ef40880d12ff8ed5f516871133ec569df03b192/spec/rails_best_practices/prepares/route_prepare_spec.rb | spec/rails_best_practices/prepares/route_prepare_spec.rb | # frozen_string_literal: true
require 'spec_helper'
module RailsBestPractices
module Prepares
describe RoutePrepare do
let(:runner) { Core::Runner.new(prepares: described_class.new) }
context 'resources' do
it 'adds resources route' do
content = <<-EOF
RailsBestPracticesCom::Application.routes.draw do
resources :posts
end
EOF
runner.prepare('config/routes.rb', content)
routes = Prepares.routes
expect(routes.size).to eq(7)
expect(routes.map(&:to_s)).to eq(
[
'PostsController#index',
'PostsController#show',
'PostsController#new',
'PostsController#create',
'PostsController#edit',
'PostsController#update',
'PostsController#destroy'
]
)
end
it 'adds multiple resources route' do
content = <<-EOF
RailsBestPracticesCom::Application.routes.draw do
resources :posts, :users
end
EOF
runner.prepare('config/routes.rb', content)
routes = Prepares.routes
expect(routes.size).to eq(14)
end
it 'adds resources route with explict controller' do
content = <<-EOF
RailsBestPracticesCom::Application.routes.draw do
resources :posts, controller: :blog_posts
end
EOF
runner.prepare('config/routes.rb', content)
routes = Prepares.routes
expect(routes.size).to eq(7)
expect(routes.map(&:to_s)).to eq(
[
'BlogPostsController#index',
'BlogPostsController#show',
'BlogPostsController#new',
'BlogPostsController#create',
'BlogPostsController#edit',
'BlogPostsController#update',
'BlogPostsController#destroy'
]
)
end
it 'adds resources route with only option' do
content = <<-EOF
RailsBestPracticesCom::Application.routes.draw do
resources :posts, only: [:index, :show, :new, :create]
end
EOF
runner.prepare('config/routes.rb', content)
routes = Prepares.routes
expect(routes.size).to eq(4)
expect(routes.map(&:to_s)).to eq(
['PostsController#index', 'PostsController#show', 'PostsController#new', 'PostsController#create']
)
end
it 'adds resources route with except option' do
content = <<-EOF
RailsBestPracticesCom::Application.routes.draw do
resources :posts, except: [:edit, :update, :destroy]
end
EOF
runner.prepare('config/routes.rb', content)
routes = Prepares.routes
expect(routes.size).to eq(4)
expect(routes.map(&:to_s)).to eq(
['PostsController#index', 'PostsController#show', 'PostsController#new', 'PostsController#create']
)
end
it 'does not add resources routes with only: :none' do
content = <<-EOF
RailsBestPracticesCom::Application.routes.draw do
resources :posts, only: :none
end
EOF
runner.prepare('config/routes.rb', content)
routes = Prepares.routes
expect(routes.size).to eq(0)
end
it 'does not add resources routes with except: :all' do
content = <<-EOF
RailsBestPracticesCom::Application.routes.draw do
resources :posts, except: :all
end
EOF
runner.prepare('config/routes.rb', content)
routes = Prepares.routes
expect(routes.size).to eq(0)
end
it 'adds resources routes with members' do
content = <<-EOF
RailsBestPracticesCom::Application.routes.draw do
namespace :admin do
resources :posts, :only => [:edit, :update] do
member do
post 'link_to/:other_id' => 'posts#link_to_post'
post 'extra_update' => 'posts#extra_update'
end
end
end
end
EOF
runner.prepare('config/routes.rb', content)
routes = Prepares.routes
expect(routes.map(&:to_s)).to eq(
[
'Admin::PostsController#edit',
'Admin::PostsController#update',
'Admin::PostsController#link_to_post',
'Admin::PostsController#extra_update'
]
)
end
it 'adds resources routes with members inline' do
content = <<-EOF
RailsBestPracticesCom::Application.routes.draw do
namespace :admin do
resources :posts, :only => [:edit, :update] do
post :link_to_post, :extra_update, :retrieve, on: :member
end
end
end
EOF
runner.prepare('config/routes.rb', content)
routes = Prepares.routes
expect(routes.map(&:to_s)).to eq(
[
'Admin::PostsController#edit',
'Admin::PostsController#update',
'Admin::PostsController#link_to_post',
'Admin::PostsController#extra_update',
'Admin::PostsController#retrieve'
]
)
end
it 'adds connect route' do
content = <<-EOF
ActionController::Routing::Routes.draw do |map|
map.connect 'vote', controller: "votes", action: "create", method: :post
end
EOF
runner.prepare('config/routes.rb', content)
routes = Prepares.routes
expect(routes.map(&:to_s)).to eq(['VotesController#create'])
end
it 'adds named route' do
content = <<-EOF
ActionController::Routing::Routes.draw do |map|
map.login '/player/login', controller: 'sessions', action: 'new', conditions: { method: :get }
end
EOF
runner.prepare('config/routes.rb', content)
routes = Prepares.routes
expect(routes.map(&:to_s)).to eq(['SessionsController#new'])
end
end
context 'resource' do
it 'adds resource route' do
content = <<-EOF
RailsBestPracticesCom::Application.routes.draw do
resource :posts
end
EOF
runner.prepare('config/routes.rb', content)
routes = Prepares.routes
expect(routes.size).to eq(6)
expect(routes.map(&:to_s)).to eq(
[
'PostsController#show',
'PostsController#new',
'PostsController#create',
'PostsController#edit',
'PostsController#update',
'PostsController#destroy'
]
)
end
it 'adds multiple resource route' do
content = <<-EOF
RailsBestPracticesCom::Application.routes.draw do
resource :posts, :users
end
EOF
runner.prepare('config/routes.rb', content)
routes = Prepares.routes
expect(routes.size).to eq(12)
end
it 'adds resource route with only option' do
content = <<-EOF
RailsBestPracticesCom::Application.routes.draw do
resource :posts, only: [:show, :new, :create]
end
EOF
runner.prepare('config/routes.rb', content)
routes = Prepares.routes
expect(routes.size).to eq(3)
expect(routes.map(&:to_s)).to eq(['PostsController#show', 'PostsController#new', 'PostsController#create'])
end
it 'adds resource route with except option' do
content = <<-EOF
RailsBestPracticesCom::Application.routes.draw do
resource :posts, except: [:edit, :update, :destroy]
end
EOF
runner.prepare('config/routes.rb', content)
routes = Prepares.routes
expect(routes.size).to eq(3)
expect(routes.map(&:to_s)).to eq(['PostsController#show', 'PostsController#new', 'PostsController#create'])
end
it 'does not add resource routes with only: :none' do
content = <<-EOF
RailsBestPracticesCom::Application.routes.draw do
resource :posts, only: :none
end
EOF
runner.prepare('config/routes.rb', content)
routes = Prepares.routes
expect(routes.size).to eq(0)
end
it 'does not add resource routes with except: :all' do
content = <<-EOF
RailsBestPracticesCom::Application.routes.draw do
resource :posts, except: :all
end
EOF
runner.prepare('config/routes.rb', content)
routes = Prepares.routes
expect(routes.size).to eq(0)
end
it 'adds resource routes with get/post/put/patch/delete routes' do
content = <<-EOF
RailsBestPracticesCom::Application.routes.draw do
resources :posts, only: [:show] do
get :list, on: :collection
collection do
get :search
match :available
end
post :create, on: :member
member do
put :update
patch :update
end
end
end
EOF
runner.prepare('config/routes.rb', content)
routes = Prepares.routes
expect(routes.size).to eq(7)
expect(routes.map(&:to_s)).to eq(
[
'PostsController#show',
'PostsController#list',
'PostsController#search',
'PostsController#available',
'PostsController#create',
'PostsController#update',
'PostsController#update'
]
)
end
it 'adds custom resources routes with {}' do
content = <<-EOF
RailsBestPracticesCom::Application.routes.draw do
resources :posts, only: [:show] do
get :inactive, on: :collection
end
end
EOF
runner.prepare('config/routes.rb', content)
routes = Prepares.routes
expect(routes.size).to eq(2)
expect(routes.map(&:to_s)).to eq(['PostsController#show', 'PostsController#inactive'])
end
it 'adds resources routes with get %w() routes' do
content = <<-EOF
RailsBestPracticesCom::Application.routes.draw do
resources :posts, only: [:show] do
collection do
get *%w(latest popular)
end
end
end
EOF
runner.prepare('config/routes.rb', content)
routes = Prepares.routes
expect(routes.size).to eq(3)
expect(routes.map(&:to_s)).to eq(
['PostsController#show', 'PostsController#latest', 'PostsController#popular']
)
end
it 'adds route with nested routes' do
content = <<-EOF
RailsBestPracticesCom::Application.routes.draw do
resources :posts
resources :comments
end
end
EOF
runner.prepare('config/routes.rb', content)
routes = Prepares.routes
expect(routes.size).to eq(14)
end
it 'adds route with namespace' do
content = <<-EOF
RailsBestPracticesCom::Application.routes.draw do
namespace :admin do
namespace :test do
resources :posts, only: [:index]
end
end
end
EOF
runner.prepare('config/routes.rb', content)
routes = Prepares.routes
expect(routes.map(&:to_s)).to eq(['Admin::Test::PostsController#index'])
end
it 'adds route with namespace, but without resources' do
content = <<-EOF
RailsBestPracticesCom::Appllication.routes.draw do
namespace :something do
get *%w(route_one route_two)
get :route_three, action: "custom_action"
end
end
EOF
runner.prepare('config/routes.rb', content)
routes = Prepares.routes
expect(routes.map(&:to_s)).to eq(
['SomethingController#route_one', 'SomethingController#route_two', 'SomethingController#custom_action']
)
end
it 'adds route with scope' do
content = <<-EOF
RailsBestPracticesCom::Application.routes.draw do
scope module: "admin" do
resources :posts, only: [:index]
end
resources :discussions, only: [:index], module: "admin"
scope "/admin" do
resources :comments, only: [:index]
end
scope "/:username", controller: :users do
get '/' => :show
scope 'topic' do
get 'preview', as: 'preview_user', action: 'preview'
end
end
end
EOF
runner.prepare('config/routes.rb', content)
routes = Prepares.routes
expect(routes.map(&:to_s)).to eq(
[
'Admin::PostsController#index',
'Admin::DiscussionsController#index',
'CommentsController#index',
'UsersController#show',
'UsersController#preview'
]
)
end
end
it 'adds route for direct get/post' do
content = <<-EOF
RailsBestPracticesCom::Application.routes.draw do
get 'posts/show'
post '/posts' => 'posts#create'
put '/posts/:id' => 'posts#update'
delete '/post/:id' => 'posts#destroy'
get '/agb' => 'high_voltage/pages#show', id: 'agb'
end
EOF
runner.prepare('config/routes.rb', content)
routes = Prepares.routes
expect(routes.size).to eq(5)
expect(routes.map(&:to_s)).to eq(
[
'PostsController#show',
'PostsController#create',
'PostsController#update',
'PostsController#destroy',
'HighVoltage::PagesController#show'
]
)
end
it 'adds routes for another get/post' do
content = <<-EOF
RailsBestPracticesCom::Application.routes.draw
get "/login", to: 'sessions#new', as: :login
end
EOF
runner.prepare('config/routes.rb', content)
routes = Prepares.routes
expect(routes.size).to eq(1)
expect(routes.first.to_s).to eq('SessionsController#new')
end
it 'adds match route' do
content = <<-EOF
RailsBestPracticesCom::Application.routes.draw do
match '/auth/:provider/callback' => 'authentications#create'
end
EOF
runner.prepare('config/routes.rb', content)
routes = Prepares.routes
expect(routes.map(&:to_s)).to eq(['AuthenticationsController#create'])
end
it 'adds match route with all actions' do
content = <<-EOF
RailsBestPracticesCom::Application.routes.draw do
match 'internal/:action/*whatever', controller: "internal"
end
EOF
runner.prepare('config/routes.rb', content)
routes = Prepares.routes
expect(routes.map(&:to_s)).to eq(['InternalController#*'])
end
it 'adds root route' do
content = <<-EOF
RailsBestPracticesCom::Application.routes.draw do
root to: 'home#index'
end
EOF
runner.prepare('config/routes.rb', content)
routes = Prepares.routes
expect(routes.map(&:to_s)).to eq(['HomeController#index'])
end
it 'adds root shortcut route' do
content = <<-EOF
RailsBestPracticesCom::Application.routes.draw do
root 'home#index'
end
EOF
runner.prepare('config/routes.rb', content)
routes = Prepares.routes
expect(routes.map(&:to_s)).to eq(['HomeController#index'])
end
it 'does nothing for default route' do
content = <<-EOF
RailsBestPracticesCom::Application.routes.draw do
match ':controller(/:action(/:id(.:format)))'
end
EOF
runner.prepare('config/routes.rb', content)
routes = Prepares.routes
expect(routes.size).to eq(0)
end
it 'does nothing for redirect' do
content = <<-EOF
RailsBestPracticesCom::Application.routes.draw do
match "/stories/:name" => redirect("/posts/%{name}")
match "/stories" => redirect {|p, req| "/posts/\#{req.subdomain}" }
end
EOF
runner.prepare('config/routes.rb', content)
routes = Prepares.routes
expect(routes.size).to eq(0)
end
it 'parses customize route in nested resources' do
content = <<-EOF
RailsBestPracticesCom::Application.routes.draw do
resources :posts do
resources :comments
post :stop
end
end
EOF
runner.prepare('config/routes.rb', content)
routes = Prepares.routes
expect(routes.last.to_s).to eq('PostsController#stop')
end
it 'parses custom route for resource with explicit to and different action name' do
content = <<-EOF
RailsBestPracticesCom::Application.routes.draw do
resources :posts do
get :halt, to: 'posts#stop'
end
end
EOF
runner.prepare('config/routes.rb', content)
routes = Prepares.routes
expect(routes.last.to_s).to eq('PostsController#stop')
end
it 'parses custom route for resource with symbol action name' do
content = <<-EOF
RailsBestPracticesCom::Application.routes.draw do
resources :posts do
get :halt, to: :stop
end
end
EOF
runner.prepare('config/routes.rb', content)
routes = Prepares.routes
expect(routes.last.to_s).to eq('PostsController#stop')
end
it 'does not take former resources for direct get/post' do
content = <<-EOF
RailsBestPracticesCom::Application.routes.draw do
resources :posts
post "sprints/stop"
end
EOF
runner.prepare('config/routes.rb', content)
routes = Prepares.routes
expect(routes.last.to_s).to eq('SprintsController#stop')
end
it 'does not parse wrong route' do
content = <<-EOF
RailsBestPracticesCom::Application.routes.draw do
match ':controller/:action' => '#index', as: :auto_complete
end
EOF
runner.prepare('config/routes.rb', content)
routes = Prepares.routes
expect(routes.size).to eq(0)
end
end
end
end
| ruby | MIT | 2ef40880d12ff8ed5f516871133ec569df03b192 | 2026-01-04T15:47:01.660067Z | false |
flyerhzm/rails_best_practices | https://github.com/flyerhzm/rails_best_practices/blob/2ef40880d12ff8ed5f516871133ec569df03b192/spec/rails_best_practices/prepares/gemfile_prepare_spec.rb | spec/rails_best_practices/prepares/gemfile_prepare_spec.rb | # frozen_string_literal: true
require 'spec_helper'
module RailsBestPractices
module Prepares
describe GemfilePrepare do
let(:runner) { Core::Runner.new(prepares: described_class.new) }
context 'gemfile' do
it 'parses gems' do
content = <<~EOF
GEM
remote: https://rubygems.org/
specs:
rails (3.2.13)
actionmailer (= 3.2.13)
actionpack (= 3.2.13)
activerecord (= 3.2.13)
activeresource (= 3.2.13)
activesupport (= 3.2.13)
bundler (~> 1.0)
railties (= 3.2.13)
mysql2 (0.3.12b6)
PLATFORMS
ruby
EOF
runner.prepare('Gemfile.lock', content)
gems = Prepares.gems
expect(gems.map(&:to_s)).to eq(['rails (3.2.13)', 'mysql2 (0.3.12b6)'])
end
end
end
end
end
| ruby | MIT | 2ef40880d12ff8ed5f516871133ec569df03b192 | 2026-01-04T15:47:01.660067Z | false |
flyerhzm/rails_best_practices | https://github.com/flyerhzm/rails_best_practices/blob/2ef40880d12ff8ed5f516871133ec569df03b192/spec/rails_best_practices/prepares/helper_prepare_spec.rb | spec/rails_best_practices/prepares/helper_prepare_spec.rb | # frozen_string_literal: true
require 'spec_helper'
module RailsBestPractices
module Prepares
describe HelperPrepare do
let(:runner) { Core::Runner.new(prepares: described_class.new) }
context 'methods' do
it 'parses helper methods' do
content = <<-EOF
module PostsHelper
def used; end
def unused; end
end
EOF
runner.prepare('app/helpers/posts_helper.rb', content)
methods = Prepares.helper_methods
expect(methods.get_methods('PostsHelper').map(&:method_name)).to eq(%w[used unused])
end
it 'parses helpers' do
content = <<-EOF
module PostsHelper
end
EOF
runner.prepare('app/helpers/posts_helper.rb', content)
content = <<-EOF
module Admin::UsersHelper
end
EOF
runner.prepare('app/helpers/users_helper.rb', content)
content = <<-EOF
module Admin
module BaseHelper
end
end
EOF
runner.prepare('app/helpers/base_helper.rb', content)
helpers = Prepares.helpers
expect(helpers.map(&:to_s)).to eq(['PostsHelper', 'Admin::UsersHelper', 'Admin', 'Admin::BaseHelper'])
end
end
end
end
end
| ruby | MIT | 2ef40880d12ff8ed5f516871133ec569df03b192 | 2026-01-04T15:47:01.660067Z | false |
flyerhzm/rails_best_practices | https://github.com/flyerhzm/rails_best_practices/blob/2ef40880d12ff8ed5f516871133ec569df03b192/spec/rails_best_practices/prepares/controller_prepare_spec.rb | spec/rails_best_practices/prepares/controller_prepare_spec.rb | # frozen_string_literal: true
require 'spec_helper'
module RailsBestPractices
module Prepares
describe ControllerPrepare do
let(:runner) { Core::Runner.new(prepares: [described_class.new, HelperPrepare.new]) }
context 'methods' do
it 'parses controller methods' do
content = <<-EOF
class PostsController < ApplicationController
def index; end
def show; end
end
EOF
runner.prepare('app/controllers/posts_controller.rb', content)
methods = Prepares.controller_methods
expect(methods.get_methods('PostsController').map(&:method_name)).to eq(%w[index show])
end
it 'parses model methods with access control' do
content = <<-EOF
class PostsController < ApplicationController
def index; end
def show; end
protected
def resources; end
private
def resource; end
end
EOF
runner.prepare('app/controllers/posts_controller.rb', content)
methods = Prepares.controller_methods
expect(methods.get_methods('PostsController').map(&:method_name)).to eq(%w[index show resources resource])
expect(methods.get_methods('PostsController', 'public').map(&:method_name)).to eq(%w[index show])
expect(methods.get_methods('PostsController', 'protected').map(&:method_name)).to eq(['resources'])
expect(methods.get_methods('PostsController', 'private').map(&:method_name)).to eq(['resource'])
end
it 'parses controller methods with module ::' do
content = <<-EOF
class Admin::Blog::PostsController < ApplicationController
def index; end
def show; end
end
EOF
runner.prepare('app/controllers/admin/posts_controller.rb', content)
methods = Prepares.controller_methods
expect(methods.get_methods('Admin::Blog::PostsController').map(&:method_name)).to eq(%w[index show])
end
it 'parses controller methods with module' do
content = <<-EOF
module Admin
module Blog
class PostsController < ApplicationController
def index; end
def show; end
end
end
end
EOF
runner.prepare('app/controllers/admin/posts_controller.rb', content)
methods = Prepares.controller_methods
expect(methods.get_methods('Admin::Blog::PostsController').map(&:method_name)).to eq(%w[index show])
end
context 'inherited_resources' do
it 'extend inherited_resources' do
content = <<-EOF
class PostsController < InheritedResources::Base
end
EOF
runner.prepare('app/controllers/posts_controller.rb', content)
methods = Prepares.controller_methods
expect(methods.get_methods('PostsController').map(&:method_name)).to eq(
%w[index show new create edit update destroy]
)
end
it 'extend inherited_resources with actions' do
content = <<-EOF
class PostsController < InheritedResources::Base
actions :index, :show
end
EOF
runner.prepare('app/controllers/posts_controller.rb', content)
methods = Prepares.controller_methods
expect(methods.get_methods('PostsController').map(&:method_name)).to eq(%w[index show])
end
it 'extend inherited_resources with all actions' do
content = <<-EOF
class PostsController < InheritedResources::Base
actions :all, except: [:show]
end
EOF
runner.prepare('app/controllers/posts_controller.rb', content)
methods = Prepares.controller_methods
expect(methods.get_methods('PostsController').map(&:method_name)).to eq(
%w[index new create edit update destroy]
)
end
it 'extend inherited_resources with all actions with no arguments' do
content = <<-EOF
class PostsController < InheritedResources::Base
actions :all
end
EOF
runner.prepare('app/controllers/posts_controller.rb', content)
methods = Prepares.controller_methods
expect(methods.get_methods('PostsController').map(&:method_name)).to eq(
%w[index show new create edit update destroy]
)
end
it 'DSL inherit_resources' do
content = <<-EOF
class PostsController
inherit_resources
end
EOF
runner.prepare('app/controllers/posts_controller.rb', content)
methods = Prepares.controller_methods
expect(methods.get_methods('PostsController').map(&:method_name)).to eq(
%w[index show new create edit update destroy]
)
end
end
end
context 'helpers' do
it 'adds helper descendant' do
content = <<-EOF
module PostsHelper
end
EOF
runner.prepare('app/helpers/posts_helper.rb', content)
content = <<-EOF
class PostsController
include PostsHelper
end
EOF
runner.prepare('app/controllers/posts_controller.rb', content)
helpers = Prepares.helpers
expect(helpers.first.descendants).to eq(['PostsController'])
end
end
end
end
end
| ruby | MIT | 2ef40880d12ff8ed5f516871133ec569df03b192 | 2026-01-04T15:47:01.660067Z | false |
flyerhzm/rails_best_practices | https://github.com/flyerhzm/rails_best_practices/blob/2ef40880d12ff8ed5f516871133ec569df03b192/spec/rails_best_practices/prepares/config_prepare_spec.rb | spec/rails_best_practices/prepares/config_prepare_spec.rb | # frozen_string_literal: true
require 'spec_helper'
module RailsBestPractices
module Prepares
describe ConfigPrepare do
let(:runner) { Core::Runner.new(prepares: described_class.new) }
context 'configs' do
it 'parses configs' do
content = <<-EOF
module RailsBestPracticesCom
class Application < Rails::Application
config.active_record.whitelist_attributes = true
end
end
EOF
runner.prepare('config/application.rb', content)
configs = Prepares.configs
expect(configs['config.active_record.whitelist_attributes']).to eq('true')
end
end
end
end
end
| ruby | MIT | 2ef40880d12ff8ed5f516871133ec569df03b192 | 2026-01-04T15:47:01.660067Z | false |
flyerhzm/rails_best_practices | https://github.com/flyerhzm/rails_best_practices/blob/2ef40880d12ff8ed5f516871133ec569df03b192/spec/rails_best_practices/prepares/mailer_prepare_spec.rb | spec/rails_best_practices/prepares/mailer_prepare_spec.rb | # frozen_string_literal: true
require 'spec_helper'
module RailsBestPractices
module Prepares
describe MailerPrepare do
let(:runner) { Core::Runner.new(prepares: described_class.new) }
it 'parses mailer names' do
content = <<-EOF
class ProjectMailer < ActionMailer::Base
end
EOF
runner.prepare('app/mailers/project_mailer.rb', content)
expect(Prepares.mailers.map(&:to_s)).to eq(['ProjectMailer'])
end
end
end
end
| ruby | MIT | 2ef40880d12ff8ed5f516871133ec569df03b192 | 2026-01-04T15:47:01.660067Z | false |
flyerhzm/rails_best_practices | https://github.com/flyerhzm/rails_best_practices/blob/2ef40880d12ff8ed5f516871133ec569df03b192/spec/rails_best_practices/prepares/model_prepare_spec.rb | spec/rails_best_practices/prepares/model_prepare_spec.rb | # frozen_string_literal: true
require 'spec_helper'
module RailsBestPractices
module Prepares
describe ModelPrepare do
let(:runner) { Core::Runner.new(prepares: described_class.new) }
context 'models' do
it 'class_name with modules ::' do
content = <<-EOF
class Blog::Post < ActiveRecord::Base
end
EOF
runner.prepare('app/models/admin/post.rb', content)
models = Prepares.models
expect(models.map(&:to_s)).to eq(['Blog::Post'])
end
it 'class_name with modules' do
content = <<-EOF
module Blog
class Post < ActiveRecord::Base
end
end
EOF
runner.prepare('app/models/admin/post.rb', content)
models = Prepares.models
expect(models.map(&:to_s)).to eq(['Blog::Post'])
end
end
context 'associations' do
it 'parses model associations' do
content = <<-EOF
class Project < ActiveRecord::Base
belongs_to :portfolio
has_one :project_manager
has_many :milestones
has_and_belongs_to_many :categories
end
EOF
runner.prepare('app/models/project.rb', content)
model_associations = Prepares.model_associations
expect(model_associations.get_association('Project', 'portfolio')).to eq(
'meta' => 'belongs_to', 'class_name' => 'Portfolio'
)
expect(model_associations.get_association('Project', 'project_manager')).to eq(
'meta' => 'has_one', 'class_name' => 'ProjectManager'
)
expect(model_associations.get_association('Project', 'milestones')).to eq(
'meta' => 'has_many', 'class_name' => 'Milestone'
)
expect(model_associations.get_association('Project', 'categories')).to eq(
'meta' => 'has_and_belongs_to_many', 'class_name' => 'Category'
)
end
context 'with class_name option' do
it 'parses belongs_to' do
content = <<-EOF
class Post < ActiveRecord::Base
belongs_to :author, "class_name" => "Person"
end
EOF
runner.prepare('app/models/post.rb', content)
model_associations = Prepares.model_associations
expect(model_associations.get_association('Post', 'author')).to eq(
'meta' => 'belongs_to', 'class_name' => 'Person'
)
end
it 'parses has_one' do
content = <<-EOF
class Project < ActiveRecord::Base
has_one :project_manager, "class_name" => "Person"
end
EOF
runner.prepare('app/models/post.rb', content)
model_associations = Prepares.model_associations
expect(model_associations.get_association('Project', 'project_manager')).to eq(
'meta' => 'has_one', 'class_name' => 'Person'
)
end
it 'parses has_many' do
content = <<-EOF
class Project < ActiveRecord::Base
has_many :people, "class_name" => "Person"
end
EOF
runner.prepare('app/models/project.rb', content)
model_associations = Prepares.model_associations
expect(model_associations.get_association('Project', 'people')).to eq(
'meta' => 'has_many', 'class_name' => 'Person'
)
end
it 'parses has_and_belongs_to_many' do
content = <<-EOF
class Citizen < ActiveRecord::Base
has_and_belongs_to_many :nations, "class_name" => "Country"
end
EOF
runner.prepare('app/models/citizen.rb', content)
model_associations = Prepares.model_associations
expect(model_associations.get_association('Citizen', 'nations')).to eq(
'meta' => 'has_and_belongs_to_many', 'class_name' => 'Country'
)
end
context 'namespace' do
it 'parses with namespace' do
content = <<-EOF
class Community < ActiveRecord::Base
has_many :members
end
EOF
runner.prepare('app/models/community.rb', content)
content = <<-EOF
class Community::Member < ActiveRecord::Base
belongs_to :community
end
EOF
runner.prepare('app/models/community/member.rb', content)
runner.after_prepare
model_associations = Prepares.model_associations
expect(model_associations.get_association('Community', 'members')).to eq(
'meta' => 'has_many', 'class_name' => 'Community::Member'
)
expect(model_associations.get_association('Community::Member', 'community')).to eq(
'meta' => 'belongs_to', 'class_name' => 'Community'
)
end
it 'parses without namespace' do
content = <<-EOF
class Community::Member::Rating < ActiveRecord::Base
belongs_to :member
end
EOF
runner.prepare('app/models/community/member/rating.rb', content)
content = <<-EOF
class Community::Member < ActiveRecord::Base
has_many :ratings
end
EOF
runner.prepare('app/models/community/member.rb', content)
runner.after_prepare
model_associations = Prepares.model_associations
expect(model_associations.get_association('Community::Member::Rating', 'member')).to eq(
'meta' => 'belongs_to', 'class_name' => 'Community::Member'
)
expect(model_associations.get_association('Community::Member', 'ratings')).to eq(
'meta' => 'has_many', 'class_name' => 'Community::Member::Rating'
)
end
end
end
context 'mongoid embeds' do
it 'parses embeds_many' do
content = <<-EOF
class Person
include Mongoid::Document
embeds_many :addresses
end
EOF
runner.prepare('app/models/person.rb', content)
model_associations = Prepares.model_associations
expect(model_associations.get_association('Person', 'addresses')).to eq(
'meta' => 'embeds_many', 'class_name' => 'Address'
)
end
it 'parses embeds_one' do
content = <<-EOF
class Lush
include Mongoid::Document
embeds_one :whiskey, class_name: "Drink", inverse_of: :alcoholic
end
EOF
runner.prepare('app/models/lush.rb', content)
model_associations = Prepares.model_associations
expect(model_associations.get_association('Lush', 'whiskey')).to eq(
'meta' => 'embeds_one', 'class_name' => 'Drink'
)
end
it 'parses embedded_in' do
content = <<-EOF
class Drink
include Mongoid::Document
embedded_in :alcoholic, class_name: "Lush", inverse_of: :whiskey
end
EOF
runner.prepare('app/models/drink.rb', content)
model_associations = Prepares.model_associations
expect(model_associations.get_association('Drink', 'alcoholic')).to eq(
'meta' => 'embedded_in', 'class_name' => 'Lush'
)
end
end
context 'mongomapper many/one' do
it 'parses one' do
content = <<-EOF
class Employee
include MongoMapper::Document
one :desk
end
EOF
runner.prepare('app/models/employee.rb', content)
model_associations = Prepares.model_associations
expect(model_associations.get_association('Employee', 'desk')).to eq(
'meta' => 'one', 'class_name' => 'Desk'
)
end
it 'parses many' do
content = <<-EOF
class Tree
include MongoMapper::Document
many :birds
end
EOF
runner.prepare('app/models/tree.rb', content)
model_associations = Prepares.model_associations
expect(model_associations.get_association('Tree', 'birds')).to eq('meta' => 'many', 'class_name' => 'Bird')
end
end
end
context 'methods' do
it 'parses model methods' do
content = <<-EOF
class Post < ActiveRecord::Base
def save; end
def find; end
end
EOF
runner.prepare('app/models/post.rb', content)
methods = Prepares.model_methods
expect(methods.get_methods('Post').map(&:method_name)).to eq(%w[save find])
end
it 'parses model methods with access control' do
content = <<-EOF
class Post < ActiveRecord::Base
def save; end
def find; end
protected
def create_or_update; end
private
def find_by_sql; end
end
EOF
runner.prepare('app/models/post.rb', content)
methods = Prepares.model_methods
expect(methods.get_methods('Post').map(&:method_name)).to eq(%w[save find create_or_update find_by_sql])
expect(methods.get_methods('Post', 'public').map(&:method_name)).to eq(%w[save find])
expect(methods.get_methods('Post', 'protected').map(&:method_name)).to eq(['create_or_update'])
expect(methods.get_methods('Post', 'private').map(&:method_name)).to eq(['find_by_sql'])
end
it 'parses model methods with module ::' do
content = <<-EOF
class Admin::Blog::Post < ActiveRecord::Base
def save; end
def find; end
end
EOF
runner.prepare('app/models/admin/blog/post.rb', content)
methods = Prepares.model_methods
expect(methods.get_methods('Admin::Blog::Post').map(&:method_name)).to eq(%w[save find])
end
it 'parses model methods with module' do
content = <<-EOF
module Admin
module Blog
class Post < ActiveRecord::Base
def save; end
def find; end
end
end
end
EOF
runner.prepare('app/models/admin/blog/post.rb', content)
methods = Prepares.model_methods
expect(methods.get_methods('Admin::Blog::Post').map(&:method_name)).to eq(%w[save find])
end
it 'does not add methods from module' do
content = <<-EOF
class Model < ActiveRecord::Base
end
EOF
runner.prepare('app/models/model.rb', content)
content = <<-EOF
module Mixin
def mixed_method
end
end
EOF
runner.prepare('app/models/mixins/mixin.rb', content)
methods = Prepares.model_methods
expect(methods.get_methods('Model')).to be_empty
end
end
context 'scope' do
it 'treats named_scope as method' do
content = <<-EOF
class Post < ActiveRecord::Base
named_scope :active, conditions: {active: true}
end
EOF
runner.prepare('app/models/post.rb', content)
methods = Prepares.model_methods
expect(methods.get_methods('Post').map(&:method_name)).to eq(['active'])
end
it 'treats scope as method' do
content = <<-EOF
class Post < ActiveRecord::Base
scope :active, where(active: true)
end
EOF
runner.prepare('app/models/post.rb', content)
methods = Prepares.model_methods
expect(methods.get_methods('Post').map(&:method_name)).to eq(['active'])
end
end
context 'alias' do
it 'treats alias as method' do
content = <<-EOF
class Post < ActiveRecord::Base
alias :new :old
end
EOF
runner.prepare('app/models/post.rb', content)
methods = Prepares.model_methods
expect(methods.get_methods('Post').map(&:method_name)).to eq(['new'])
end
it 'treats alias_method as method' do
content = <<-EOF
class Post < ActiveRecord::Base
alias_method :new, :old
end
EOF
runner.prepare('app/models/post.rb', content)
methods = Prepares.model_methods
expect(methods.get_methods('Post').map(&:method_name)).to eq(['new'])
end
it 'treats alias_method_chain as method' do
content = <<-EOF
class Post < ActiveRecord::Base
alias_method_chain :method, :feature
end
EOF
runner.prepare('app/models/post.rb', content)
methods = Prepares.model_methods
expect(methods.get_methods('Post').map(&:method_name)).to eq(%w[method_with_feature method])
end
end
context 'attributes' do
it 'parses mongoid field' do
content = <<-EOF
class Post
include Mongoid::Document
field :title
field :tags, type: Array
field :comments_count, type: Integer
field :deleted_at, type: DateTime
field :active, type: Boolean
end
EOF
runner.prepare('app/models/post.rb', content)
model_attributes = Prepares.model_attributes
expect(model_attributes.get_attribute_type('Post', 'title')).to eq('String')
expect(model_attributes.get_attribute_type('Post', 'tags')).to eq('Array')
expect(model_attributes.get_attribute_type('Post', 'comments_count')).to eq('Integer')
expect(model_attributes.get_attribute_type('Post', 'deleted_at')).to eq('DateTime')
expect(model_attributes.get_attribute_type('Post', 'active')).to eq('Boolean')
end
it 'parses mongomapper field' do
content = <<-EOF
class Post
include MongoMapper::Document
key :first_name, String
key :last_name, String
key :age, Integer
key :born_at, Time
key :active, Boolean
key :fav_colors, Array
end
EOF
runner.prepare('app/models/post.rb', content)
model_attributes = Prepares.model_attributes
expect(model_attributes.get_attribute_type('Post', 'first_name')).to eq('String')
expect(model_attributes.get_attribute_type('Post', 'last_name')).to eq('String')
expect(model_attributes.get_attribute_type('Post', 'age')).to eq('Integer')
expect(model_attributes.get_attribute_type('Post', 'born_at')).to eq('Time')
expect(model_attributes.get_attribute_type('Post', 'active')).to eq('Boolean')
expect(model_attributes.get_attribute_type('Post', 'fav_colors')).to eq('Array')
end
end
context 'no error' do
it 'raiseds for finder_sql option' do
content = <<-EOF
class EventSubscription < ActiveRecord::Base
has_many :event_notification_template, finder_sql: ?
end
EOF
content =
content.sub(
'?',
'\'SELECT event_notification_templates.* from event_notification_templates where event_type_id=#{event_type_id} and delivery_method_id=#{delivery_method_id}\''
)
expect { runner.prepare('app/models/event_subscription.rb', content) }.not_to raise_error
end
end
end
end
end
| ruby | MIT | 2ef40880d12ff8ed5f516871133ec569df03b192 | 2026-01-04T15:47:01.660067Z | false |
flyerhzm/rails_best_practices | https://github.com/flyerhzm/rails_best_practices/blob/2ef40880d12ff8ed5f516871133ec569df03b192/spec/rails_best_practices/prepares/initializer_prepare_spec.rb | spec/rails_best_practices/prepares/initializer_prepare_spec.rb | # frozen_string_literal: true
require 'spec_helper'
module RailsBestPractices
module Prepares
describe InitializerPrepare do
let(:runner) { Core::Runner.new(prepares: described_class.new) }
context 'initializers' do
it 'sets include_forbidden_attributes_protection config' do
content = <<-EOF
class AR
ActiveRecord::Base.send(:include, ActiveModel::ForbiddenAttributesProtection)
end
EOF
runner.prepare('config/initializers/ar.rb', content)
configs = Prepares.configs
expect(configs['railsbp.include_forbidden_attributes_protection']).to eq('true')
end
it 'does not set include_forbidden_attributes_protection config' do
content = <<-EOF
class AR
end
EOF
runner.prepare('config/initializers/ar.rb', content)
configs = Prepares.configs
expect(configs['railsbp.include_forbidden_attributes_protection']).to be_nil
end
end
end
end
end
| ruby | MIT | 2ef40880d12ff8ed5f516871133ec569df03b192 | 2026-01-04T15:47:01.660067Z | false |
flyerhzm/rails_best_practices | https://github.com/flyerhzm/rails_best_practices/blob/2ef40880d12ff8ed5f516871133ec569df03b192/spec/rails_best_practices/prepares/schema_prepare_spec.rb | spec/rails_best_practices/prepares/schema_prepare_spec.rb | # frozen_string_literal: true
require 'spec_helper'
module RailsBestPractices
module Prepares
describe SchemaPrepare do
let(:runner) { Core::Runner.new(prepares: described_class.new) }
it 'parses model attributes' do
content = <<-EOF
ActiveRecord::Schema.define(version: 20110319172136) do
create_table "posts", force: true do |t|
t.string "title"
t.text "body", limit: 16777215
t.datetime "created_at"
t.integer "user_id"
t.integer "comments_count", default: 0
t.boolean "published", default: false, null: false
end
end
EOF
runner.prepare('db/schema.rb', content)
model_attributes = Prepares.model_attributes
expect(model_attributes.get_attribute_type('Post', 'title')).to eq('string')
expect(model_attributes.get_attribute_type('Post', 'body')).to eq('text')
expect(model_attributes.get_attribute_type('Post', 'created_at')).to eq('datetime')
expect(model_attributes.get_attribute_type('Post', 'user_id')).to eq('integer')
expect(model_attributes.get_attribute_type('Post', 'comments_count')).to eq('integer')
expect(model_attributes.get_attribute_type('Post', 'published')).to eq('boolean')
end
end
end
end
| ruby | MIT | 2ef40880d12ff8ed5f516871133ec569df03b192 | 2026-01-04T15:47:01.660067Z | false |
flyerhzm/rails_best_practices | https://github.com/flyerhzm/rails_best_practices/blob/2ef40880d12ff8ed5f516871133ec569df03b192/spec/rails_best_practices/lexicals/remove_tab_check_spec.rb | spec/rails_best_practices/lexicals/remove_tab_check_spec.rb | # frozen_string_literal: true
require 'spec_helper'
module RailsBestPractices
module Lexicals
describe RemoveTabCheck do
let(:runner) { Core::Runner.new(lexicals: described_class.new) }
it 'removes tab' do
content = <<-EOF
class User < ActiveRecord::Base
has_many :projects
end
EOF
content = content.gsub("\n", "\t\n")
runner.lexical('app/models/user.rb', content)
expect(runner.errors.size).to eq(1)
expect(runner.errors[0].to_s).to eq('app/models/user.rb:1 - remove tab, use spaces instead')
end
it 'removes tab with third line' do
content = <<-EOF
class User < ActiveRecord::Base
has_many :projects
\t
end
EOF
runner.lexical('app/models/user.rb', content)
expect(runner.errors.size).to eq(1)
expect(runner.errors[0].to_s).to eq('app/models/user.rb:3 - remove tab, use spaces instead')
end
it 'does not remove trailing whitespace' do
content = <<-EOF
class User < ActiveRecord::Base
has_many :projects
end
EOF
runner.lexical('app/models/user.rb', content)
expect(runner.errors.size).to eq(0)
end
it 'does not check ignored files' do
runner = Core::Runner.new(lexicals: described_class.new(ignored_files: /user/))
content = <<-EOF
class User < ActiveRecord::Base
has_many :projects
\t
end
EOF
content = content.gsub("\n", "\t\n")
runner.lexical('app/models/user.rb', content)
expect(runner.errors.size).to eq(0)
end
end
end
end
| ruby | MIT | 2ef40880d12ff8ed5f516871133ec569df03b192 | 2026-01-04T15:47:01.660067Z | false |
flyerhzm/rails_best_practices | https://github.com/flyerhzm/rails_best_practices/blob/2ef40880d12ff8ed5f516871133ec569df03b192/spec/rails_best_practices/lexicals/remove_trailing_whitespace_check_spec.rb | spec/rails_best_practices/lexicals/remove_trailing_whitespace_check_spec.rb | # frozen_string_literal: true
require 'spec_helper'
module RailsBestPractices
module Lexicals
describe RemoveTrailingWhitespaceCheck do
let(:runner) { Core::Runner.new(lexicals: described_class.new) }
it 'removes trailing whitespace' do
content = <<-EOF
class User < ActiveRecord::Base
has_many :projects
end
EOF
content = content.gsub("\n", " \n")
runner.lexical('app/models/user.rb', content)
expect(runner.errors.size).to eq(1)
expect(runner.errors[0].to_s).to eq('app/models/user.rb:1 - remove trailing whitespace')
end
it 'removes whitespace with third line' do
content = <<-EOF
class User < ActiveRecord::Base
has_many :projects
end
EOF
content = content.gsub("d\n", "d \n")
runner.lexical('app/models/user.rb', content)
expect(runner.errors.size).to eq(1)
expect(runner.errors[0].to_s).to eq('app/models/user.rb:3 - remove trailing whitespace')
end
it 'does not remove trailing whitespace' do
content = <<-EOF
class User < ActiveRecord::Base
has_many :projects
end
EOF
runner.lexical('app/models/user.rb', content)
expect(runner.errors.size).to eq(0)
end
it 'does not check ignored files' do
runner = Core::Runner.new(lexicals: described_class.new(ignored_files: /user/))
content = <<-EOF
class User < ActiveRecord::Base
has_many :projects
end
EOF
content = content.gsub("\n", " \n")
runner.lexical('app/models/user.rb', content)
expect(runner.errors.size).to eq(0)
end
end
end
end
| ruby | MIT | 2ef40880d12ff8ed5f516871133ec569df03b192 | 2026-01-04T15:47:01.660067Z | false |
flyerhzm/rails_best_practices | https://github.com/flyerhzm/rails_best_practices/blob/2ef40880d12ff8ed5f516871133ec569df03b192/spec/rails_best_practices/lexicals/long_line_check_spec.rb | spec/rails_best_practices/lexicals/long_line_check_spec.rb | # frozen_string_literal: true
require 'spec_helper'
module RailsBestPractices
module Lexicals
describe LongLineCheck do
it 'finds long lines' do
runner = Core::Runner.new(lexicals: described_class.new)
content = <<~EOF
class User < ActiveRecord::Base
# 81 Chars
xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
# 80 Chars
xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
end
EOF
content = content.gsub("\n", "\t\n")
runner.lexical('app/models/user.rb', content)
expect(runner.errors.size).to eq(1)
expect(runner.errors[0].to_s).to eq('app/models/user.rb:3 - line is longer than 80 characters (81 characters)')
end
it 'finds long lines with own max size' do
runner = Core::Runner.new(lexicals: described_class.new('max_line_length' => 90))
content = <<~EOF
class User < ActiveRecord::Base
# 91 Chars
xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
# 90 Chars
xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
end
EOF
content = content.gsub("\n", "\t\n")
runner.lexical('app/models/user.rb', content)
expect(runner.errors.size).to eq(1)
expect(runner.errors[0].to_s).to eq('app/models/user.rb:3 - line is longer than 90 characters (91 characters)')
end
it 'does not check non .rb files' do
runner = Core::Runner.new(lexicals: described_class.new)
content =
'
xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
'
runner.lexical('app/views/users/index.html.erb', content)
expect(runner.errors.size).to eq(0)
end
it 'does not check ignored files' do
runner = Core::Runner.new(lexicals: described_class.new(max_line_length: 80, ignored_files: /user/))
content = <<~EOF
class User < ActiveRecord::Base
# 81 Chars
xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
end
EOF
content = content.gsub("\n", "\t\n")
runner.lexical('app/models/user.rb', content)
expect(runner.errors.size).to eq(0)
end
end
end
end
| ruby | MIT | 2ef40880d12ff8ed5f516871133ec569df03b192 | 2026-01-04T15:47:01.660067Z | false |
flyerhzm/rails_best_practices | https://github.com/flyerhzm/rails_best_practices/blob/2ef40880d12ff8ed5f516871133ec569df03b192/spec/rails_best_practices/core/methods_spec.rb | spec/rails_best_practices/core/methods_spec.rb | # frozen_string_literal: true
require 'spec_helper'
module RailsBestPractices::Core
describe Methods do
let(:methods) { described_class.new }
before do
methods.add_method('Post', 'create')
methods.add_method('Post', 'destroy')
methods.add_method('Post', 'save_or_update', {}, 'protected')
methods.add_method('Post', 'find_by_sql', {}, 'private')
methods.add_method('Comment', 'create')
end
it 'get_methodses' do
expect(methods.get_methods('Post').map(&:method_name)).to eq(%w[create destroy save_or_update find_by_sql])
expect(methods.get_methods('Post', 'public').map(&:method_name)).to eq(%w[create destroy])
expect(methods.get_methods('Post', 'protected').map(&:method_name)).to eq(['save_or_update'])
expect(methods.get_methods('Post', 'private').map(&:method_name)).to eq(['find_by_sql'])
expect(methods.get_methods('Comment').map(&:method_name)).to eq(['create'])
end
it 'has_method?s' do
expect(methods).to be_has_method('Post', 'create', 'public')
expect(methods).to be_has_method('Post', 'destroy', 'public')
expect(methods).not_to be_has_method('Post', 'save_or_update', 'public')
expect(methods).to be_has_method('Post', 'save_or_update', 'protected')
expect(methods).not_to be_has_method('Post', 'find_by_sql', 'public')
expect(methods).to be_has_method('Post', 'find_by_sql', 'private')
expect(methods).not_to be_has_method('Comment', 'destroy')
end
it 'get_methods' do
expect(methods.get_method('Post', 'create', 'public')).not_to be_nil
expect(methods.get_method('Post', 'create', 'protected')).to be_nil
end
it 'get_all_unused_methodses' do
methods.get_method('Comment', 'create').mark_used
expect(methods.get_all_unused_methods('public').map(&:method_name)).to eq(%w[create destroy])
expect(methods.get_all_unused_methods('protected').map(&:method_name)).to eq(['save_or_update'])
expect(methods.get_all_unused_methods('private').map(&:method_name)).to eq(['find_by_sql'])
expect(methods.get_all_unused_methods.map(&:method_name)).to eq(%w[create destroy save_or_update find_by_sql])
end
end
end
| ruby | MIT | 2ef40880d12ff8ed5f516871133ec569df03b192 | 2026-01-04T15:47:01.660067Z | false |
flyerhzm/rails_best_practices | https://github.com/flyerhzm/rails_best_practices/blob/2ef40880d12ff8ed5f516871133ec569df03b192/spec/rails_best_practices/core/mailers_spec.rb | spec/rails_best_practices/core/mailers_spec.rb | # frozen_string_literal: true
require 'spec_helper'
module RailsBestPractices::Core
describe Mailers do
it { is_expected.to be_a_kind_of Klasses }
end
end
| ruby | MIT | 2ef40880d12ff8ed5f516871133ec569df03b192 | 2026-01-04T15:47:01.660067Z | false |
flyerhzm/rails_best_practices | https://github.com/flyerhzm/rails_best_practices/blob/2ef40880d12ff8ed5f516871133ec569df03b192/spec/rails_best_practices/core/except_methods_spec.rb | spec/rails_best_practices/core/except_methods_spec.rb | # frozen_string_literal: true
require 'spec_helper'
module RailsBestPractices::Core
describe Check::Exceptable do
let(:method) { Method.new 'BlogPost', 'approve', 'public', {} }
context 'wildcard class and method' do
let(:except_method) { '*#*' }
it 'matches' do
expect(described_class.matches(method, except_method)).to eql true
end
end
context 'wildcard class and matching explicit method' do
let(:except_method) { '*#approve' }
it 'matches' do
expect(described_class.matches(method, except_method)).to eql true
end
end
context 'wildcard class and non-matching explicit method' do
let(:except_method) { '*#disapprove' }
it 'matches' do
expect(described_class.matches(method, except_method)).to eql false
end
end
context 'matching class and wildcard method' do
let(:except_method) { 'BlogPost#*' }
it 'matches' do
expect(described_class.matches(method, except_method)).to eql true
end
end
context 'non-matching class and wildcard method' do
let(:except_method) { 'User#*' }
it 'matches' do
expect(described_class.matches(method, except_method)).to eql false
end
end
context 'matching class and matching method' do
let(:except_method) { 'BlogPost#approve' }
it 'matches' do
expect(described_class.matches(method, except_method)).to eql true
end
end
context 'non-matching class and non-matching method' do
let(:except_method) { 'User#disapprove' }
it 'matches' do
expect(described_class.matches(method, except_method)).to eql false
end
end
end
end
| ruby | MIT | 2ef40880d12ff8ed5f516871133ec569df03b192 | 2026-01-04T15:47:01.660067Z | false |
flyerhzm/rails_best_practices | https://github.com/flyerhzm/rails_best_practices/blob/2ef40880d12ff8ed5f516871133ec569df03b192/spec/rails_best_practices/core/klasses_spec.rb | spec/rails_best_practices/core/klasses_spec.rb | # frozen_string_literal: true
require 'spec_helper'
module RailsBestPractices::Core
describe Klasses do
it { is_expected.to be_a_kind_of Array }
context 'Klass' do
describe '#class_name' do
it 'gets class name without module' do
klass = Klass.new('BlogPost', 'Post', [])
expect(klass.class_name).to eq('BlogPost')
end
it 'gets class name with moduel' do
klass = Klass.new('BlogPost', 'Post', ['Admin'])
expect(klass.class_name).to eq('Admin::BlogPost')
end
end
describe '#extend_class_name' do
it 'gets extend class name without module' do
klass = Klass.new('BlogPost', 'Post', [])
expect(klass.extend_class_name).to eq('Post')
end
it 'gets extend class name with module' do
klass = Klass.new('BlogPost', 'Post', ['Admin'])
expect(klass.extend_class_name).to eq('Admin::Post')
end
end
it 'gets to_s equal to class_name' do
klass = Klass.new('BlogPost', 'Post', ['Admin'])
expect(klass.to_s).to eq(klass.class_name)
end
end
end
end
| ruby | MIT | 2ef40880d12ff8ed5f516871133ec569df03b192 | 2026-01-04T15:47:01.660067Z | false |
flyerhzm/rails_best_practices | https://github.com/flyerhzm/rails_best_practices/blob/2ef40880d12ff8ed5f516871133ec569df03b192/spec/rails_best_practices/core/models_spec.rb | spec/rails_best_practices/core/models_spec.rb | # frozen_string_literal: true
require 'spec_helper'
module RailsBestPractices::Core
describe Models do
it { is_expected.to be_a_kind_of Klasses }
end
end
| ruby | MIT | 2ef40880d12ff8ed5f516871133ec569df03b192 | 2026-01-04T15:47:01.660067Z | false |
flyerhzm/rails_best_practices | https://github.com/flyerhzm/rails_best_practices/blob/2ef40880d12ff8ed5f516871133ec569df03b192/spec/rails_best_practices/core/check_spec.rb | spec/rails_best_practices/core/check_spec.rb | # frozen_string_literal: true
require 'spec_helper'
module RailsBestPractices::Core
describe Check do
let(:check) { described_class.new }
context 'debug' do
it 'is debug mode' do
described_class.debug
expect(described_class).to be_debug
described_class.class_eval { @debug = false }
end
end
end
end
| ruby | MIT | 2ef40880d12ff8ed5f516871133ec569df03b192 | 2026-01-04T15:47:01.660067Z | false |
flyerhzm/rails_best_practices | https://github.com/flyerhzm/rails_best_practices/blob/2ef40880d12ff8ed5f516871133ec569df03b192/spec/rails_best_practices/core/modules_spec.rb | spec/rails_best_practices/core/modules_spec.rb | # frozen_string_literal: true
require 'spec_helper'
module RailsBestPractices::Core
describe Modules do
it { is_expected.to be_a_kind_of Array }
context 'Modules' do
before do
@mod = Mod.new('PostsHelper', [])
end
subject { described_class.new.tap { |modules| modules << @mod } }
it 'adds descendant to the corresponding module' do
expect(@mod).to receive(:add_descendant).with('PostsController')
subject.add_module_descendant('PostsHelper', 'PostsController')
end
end
context 'Mod' do
subject do
Mod.new('UsersHelper', ['Admin']).tap do |mod|
mod.add_descendant('Admin::UsersController')
end
end
it { expect(subject.to_s).to eq('Admin::UsersHelper') }
it { expect(subject.descendants).to eq(['Admin::UsersController']) }
end
end
end
| ruby | MIT | 2ef40880d12ff8ed5f516871133ec569df03b192 | 2026-01-04T15:47:01.660067Z | false |
flyerhzm/rails_best_practices | https://github.com/flyerhzm/rails_best_practices/blob/2ef40880d12ff8ed5f516871133ec569df03b192/spec/rails_best_practices/core/gems_spec.rb | spec/rails_best_practices/core/gems_spec.rb | # frozen_string_literal: true
require 'spec_helper'
module RailsBestPractices::Core
describe Gems do
it { is_expected.to be_a_kind_of Array }
let(:gems) { described_class.new }
before do
gems << Gem.new('rails', '4.0.0')
gems << Gem.new('mysql2', '0.2.0')
end
describe '#has_gem?' do
it 'has rails gem' do
expect(gems).to be_has_gem 'rails'
end
it "hasn't sinatra gem" do
expect(gems).not_to be_has_gem 'sinatra'
end
end
describe '#gem_version' do
it 'gets rails version' do
expect(gems.gem_version('rails')).to eq '4.0.0'
end
end
end
end
| ruby | MIT | 2ef40880d12ff8ed5f516871133ec569df03b192 | 2026-01-04T15:47:01.660067Z | false |
flyerhzm/rails_best_practices | https://github.com/flyerhzm/rails_best_practices/blob/2ef40880d12ff8ed5f516871133ec569df03b192/spec/rails_best_practices/core/model_attributes_spec.rb | spec/rails_best_practices/core/model_attributes_spec.rb | # frozen_string_literal: true
require 'spec_helper'
module RailsBestPractices::Core
describe ModelAttributes do
let(:model_attributes) { described_class.new }
before do
model_attributes.add_attribute('Post', 'title', :string)
model_attributes.add_attribute('Post', 'user_id', :integer)
end
it 'gets model attributes' do
expect(model_attributes.get_attribute_type('Post', 'title')).to eq(:string)
expect(model_attributes.get_attribute_type('Post', 'user_id')).to eq(:integer)
expect(model_attributes.get_attribute_type('Post', 'unknonw')).to be_nil
end
it 'checks is model attributes' do
expect(model_attributes.is_attribute?('Post', 'title')).to be true
expect(model_attributes.is_attribute?('Post', 'user_id')).to be true
expect(model_attributes.is_attribute?('Post', 'unknonw')).to be false
end
end
end
| ruby | MIT | 2ef40880d12ff8ed5f516871133ec569df03b192 | 2026-01-04T15:47:01.660067Z | false |
flyerhzm/rails_best_practices | https://github.com/flyerhzm/rails_best_practices/blob/2ef40880d12ff8ed5f516871133ec569df03b192/spec/rails_best_practices/core/checks_loader_spec.rb | spec/rails_best_practices/core/checks_loader_spec.rb | # frozen_string_literal: true
require 'spec_helper'
module RailsBestPractices::Core
describe ChecksLoader do
let(:checks_loader) { described_class.new(RailsBestPractices::Analyzer::DEFAULT_CONFIG) }
describe 'load_lexicals' do
it 'loads lexical checks from the default configuration' do
lexicals = checks_loader.load_lexicals
expect(lexicals.map(&:class)).to include(RailsBestPractices::Lexicals::RemoveTrailingWhitespaceCheck)
end
end
describe 'load_reviews' do
it 'loads the reviews from the default the configuration' do
reviews = checks_loader.load_reviews
expect(reviews.map(&:class)).to include(RailsBestPractices::Reviews::AlwaysAddDbIndexReview)
end
end
end
end
| ruby | MIT | 2ef40880d12ff8ed5f516871133ec569df03b192 | 2026-01-04T15:47:01.660067Z | false |
flyerhzm/rails_best_practices | https://github.com/flyerhzm/rails_best_practices/blob/2ef40880d12ff8ed5f516871133ec569df03b192/spec/rails_best_practices/core/model_associations_spec.rb | spec/rails_best_practices/core/model_associations_spec.rb | # frozen_string_literal: true
require 'spec_helper'
module RailsBestPractices::Core
describe ModelAssociations do
let(:model_associations) { described_class.new }
before do
model_associations.add_association('Project', 'project_manager', 'belongs_to')
model_associations.add_association('Project', 'people', 'has_many', 'Person')
end
it 'gets model associations' do
expect(model_associations.get_association('Project', 'project_manager')).to eq(
'meta' => 'belongs_to', 'class_name' => 'ProjectManager'
)
expect(model_associations.get_association('Project', 'people')).to eq(
'meta' => 'has_many', 'class_name' => 'Person'
)
expect(model_associations.get_association('Project', 'unknown')).to be_nil
end
it 'checks is model associatiosn' do
expect(model_associations.is_association?('Project', 'project_manager')).to eq true
expect(model_associations.is_association?('Project', 'people')).to eq true
expect(model_associations.is_association?('Project', 'unknown')).to eq false
end
end
end
| ruby | MIT | 2ef40880d12ff8ed5f516871133ec569df03b192 | 2026-01-04T15:47:01.660067Z | false |
flyerhzm/rails_best_practices | https://github.com/flyerhzm/rails_best_practices/blob/2ef40880d12ff8ed5f516871133ec569df03b192/spec/rails_best_practices/core/helpers_spec.rb | spec/rails_best_practices/core/helpers_spec.rb | # frozen_string_literal: true
require 'spec_helper'
module RailsBestPractices::Core
describe Helpers do
it { is_expected.to be_a_kind_of Modules }
end
end
| ruby | MIT | 2ef40880d12ff8ed5f516871133ec569df03b192 | 2026-01-04T15:47:01.660067Z | false |
flyerhzm/rails_best_practices | https://github.com/flyerhzm/rails_best_practices/blob/2ef40880d12ff8ed5f516871133ec569df03b192/spec/rails_best_practices/core/routes_spec.rb | spec/rails_best_practices/core/routes_spec.rb | # frozen_string_literal: true
require 'spec_helper'
module RailsBestPractices::Core
describe Routes do
let(:routes) { described_class.new }
it 'adds route' do
routes.add_route(%w[admin test], 'posts', 'new')
expect(routes.map(&:to_s)).to eq(['Admin::Test::PostsController#new'])
end
context 'route' do
it 'adds namesapces, controller name and action name' do
route = Route.new(%w[admin test], 'posts', 'new')
expect(route.to_s).to eq('Admin::Test::PostsController#new')
end
it 'adds controller name with namespace' do
route = Route.new(['admin'], 'test/posts', 'new')
expect(route.to_s).to eq('Admin::Test::PostsController#new')
end
it 'adds routes without controller' do
route = Route.new(['posts'], nil, 'new')
expect(route.to_s).to eq('PostsController#new')
end
end
end
end
| ruby | MIT | 2ef40880d12ff8ed5f516871133ec569df03b192 | 2026-01-04T15:47:01.660067Z | false |
flyerhzm/rails_best_practices | https://github.com/flyerhzm/rails_best_practices/blob/2ef40880d12ff8ed5f516871133ec569df03b192/spec/rails_best_practices/core/error_spec.rb | spec/rails_best_practices/core/error_spec.rb | # frozen_string_literal: true
require 'spec_helper'
module RailsBestPractices::Core
describe Error do
it 'returns error with filename, line number and message' do
expect(
described_class.new(
filename: 'app/models/user.rb', line_number: '100', message: 'not good', type: 'BogusReview'
).to_s
).to eq('app/models/user.rb:100 - not good')
end
it 'returns short filename' do
Runner.base_path = '../rails-bestpractices.com'
expect(
described_class.new(
filename: '../rails-bestpractices.com/app/models/user.rb',
line_number: '100',
message: 'not good',
type: 'BogusReview'
).short_filename
).to eq('app/models/user.rb')
end
it 'returns first line number' do
expect(
described_class.new(
filename: 'app/models/user.rb', line_number: '50,70,100', message: 'not good', type: 'BogusReview'
).first_line_number
).to eq('50')
end
end
end
| ruby | MIT | 2ef40880d12ff8ed5f516871133ec569df03b192 | 2026-01-04T15:47:01.660067Z | false |
flyerhzm/rails_best_practices | https://github.com/flyerhzm/rails_best_practices/blob/2ef40880d12ff8ed5f516871133ec569df03b192/spec/rails_best_practices/core/controllers_spec.rb | spec/rails_best_practices/core/controllers_spec.rb | # frozen_string_literal: true
require 'spec_helper'
module RailsBestPractices::Core
describe Controllers do
it { is_expected.to be_a_kind_of Klasses }
end
end
| ruby | MIT | 2ef40880d12ff8ed5f516871133ec569df03b192 | 2026-01-04T15:47:01.660067Z | false |
flyerhzm/rails_best_practices | https://github.com/flyerhzm/rails_best_practices/blob/2ef40880d12ff8ed5f516871133ec569df03b192/spec/rails_best_practices/core/runner_spec.rb | spec/rails_best_practices/core/runner_spec.rb | # frozen_string_literal: true
require 'spec_helper'
module RailsBestPractices::Core
describe Runner do
describe 'load_plugin_reviews' do
shared_examples_for 'load_plugin_reviews' do
it 'loads plugins in lib/rails_best_practices/plugins/reviews' do
runner = described_class.new
expect(runner.instance_variable_get('@reviews').map(&:class)).to include(
RailsBestPractices::Plugins::Reviews::NotUseRailsRootReview
)
end
end
context 'given a path that ends with a slash' do
before { described_class.base_path = 'spec/fixtures/' }
it_behaves_like 'load_plugin_reviews'
end
context 'given a path that does not end with a slash' do
before { described_class.base_path = 'spec/fixtures' }
it_behaves_like 'load_plugin_reviews'
end
end
end
end
| ruby | MIT | 2ef40880d12ff8ed5f516871133ec569df03b192 | 2026-01-04T15:47:01.660067Z | false |
flyerhzm/rails_best_practices | https://github.com/flyerhzm/rails_best_practices/blob/2ef40880d12ff8ed5f516871133ec569df03b192/spec/rails_best_practices/core/configs_spec.rb | spec/rails_best_practices/core/configs_spec.rb | # frozen_string_literal: true
require 'spec_helper'
module RailsBestPractices::Core
describe Configs do
it { is_expected.to be_a_kind_of Hash }
end
end
| ruby | MIT | 2ef40880d12ff8ed5f516871133ec569df03b192 | 2026-01-04T15:47:01.660067Z | false |
flyerhzm/rails_best_practices | https://github.com/flyerhzm/rails_best_practices/blob/2ef40880d12ff8ed5f516871133ec569df03b192/lib/rails_best_practices.rb | lib/rails_best_practices.rb | # frozen_string_literal: true
require 'code_analyzer'
require 'require_all'
require 'rails_best_practices/core'
require 'rails_best_practices/colorize'
require 'rails_best_practices/analyzer'
require 'rails_best_practices/lexicals'
require 'rails_best_practices/prepares'
require 'rails_best_practices/reviews'
require 'rails_best_practices/inline_disables'
require 'rails_best_practices/option_parser'
require 'rails_best_practices/cli'
module RailsBestPractices; end
| ruby | MIT | 2ef40880d12ff8ed5f516871133ec569df03b192 | 2026-01-04T15:47:01.660067Z | false |
flyerhzm/rails_best_practices | https://github.com/flyerhzm/rails_best_practices/blob/2ef40880d12ff8ed5f516871133ec569df03b192/lib/rails_best_practices/command.rb | lib/rails_best_practices/command.rb | # frozen_string_literal: true
require 'optparse'
options = RailsBestPractices::OptionParser.parse!
if !ARGV.empty? && !File.exist?(ARGV.first)
puts "#{ARGV.first} doesn't exist"
exit 1
end
if options['generate']
RailsBestPractices::Analyzer.new(ARGV.first).generate
else
analyzer = RailsBestPractices::Analyzer.new(ARGV.first, options)
analyzer.analyze
analyzer.output
exit !analyzer.runner.errors.empty? ? 1 : 0
end
| ruby | MIT | 2ef40880d12ff8ed5f516871133ec569df03b192 | 2026-01-04T15:47:01.660067Z | false |
flyerhzm/rails_best_practices | https://github.com/flyerhzm/rails_best_practices/blob/2ef40880d12ff8ed5f516871133ec569df03b192/lib/rails_best_practices/core.rb | lib/rails_best_practices/core.rb | # frozen_string_literal: true
require_rel 'core'
require_rel 'core_ext'
| ruby | MIT | 2ef40880d12ff8ed5f516871133ec569df03b192 | 2026-01-04T15:47:01.660067Z | false |
flyerhzm/rails_best_practices | https://github.com/flyerhzm/rails_best_practices/blob/2ef40880d12ff8ed5f516871133ec569df03b192/lib/rails_best_practices/version.rb | lib/rails_best_practices/version.rb | # frozen_string_literal: true
module RailsBestPractices
VERSION = '1.23.3'
end
| ruby | MIT | 2ef40880d12ff8ed5f516871133ec569df03b192 | 2026-01-04T15:47:01.660067Z | false |
flyerhzm/rails_best_practices | https://github.com/flyerhzm/rails_best_practices/blob/2ef40880d12ff8ed5f516871133ec569df03b192/lib/rails_best_practices/option_parser.rb | lib/rails_best_practices/option_parser.rb | # frozen_string_literal: true
require 'optparse'
module RailsBestPractices
class OptionParser
# Usage: rails_best_practices [options] path
# -d, --debug debug mode
# --silent silent mode
# -f, --format FORMAT output format (text, html, yaml, json, xml)
# --output-file FILE output html file for the analyzing result
# --without-color only output plain text without color
# --with-atom open file by atom in html format
# --with-textmate open file by textmate in html format
# --with-vscode open file by vscode in html format
# --with-sublime open file by sublime in html format (requires subl-handler)
# --with-mvim open file by mvim in html format
# --with-github GITHUB_NAME open file on github in html format, GITHUB_NAME is like railsbp/rails-bestpractices.com
# --with-git display git commit and username, only support html format
# --with-hg display hg commit and username, only support html format
# --template TEMPLATE customize erb template
# --vendor include vendor files
# --spec include spec files
# --test include test files
# --features include features files
# -x, --exclude PATTERNS don't analyze files matching a pattern
# (comma-separated regexp list)
# -o, --only PATTERNS analyze files only matching a pattern
# (comma-separated regexp list)
# -g, --generate generate configuration yaml
# -v, --version show this version
# -h, --help show this message
def self.parse!(argv = ARGV)
options = {}
OptParse.new do |opts|
opts.default_argv = argv
opts.banner = 'Usage: rails_best_practices [options] path'
opts.on('-d', '--debug', 'Debug mode') do
options['debug'] = true
end
opts.on('-f', '--format FORMAT', 'output format (text, html, yaml, json, xml)') do |format|
options['format'] = format
end
opts.on('--without-color', 'only output plain text without color') do
options['without-color'] = true
end
opts.on('--with-atom', 'open file by atom in html format') do
options['with-atom'] = true
end
opts.on('--with-textmate', 'open file by textmate in html format') do
options['with-textmate'] = true
end
opts.on('--with-vscode', 'open file by vscode in html format') do
options['with-vscode'] = true
end
opts.on('--with-sublime', 'open file by sublime in html format') do
options['with-sublime'] = true
end
opts.on('--with-mvim', 'open file by mvim in html format') do
options['with-mvim'] = true
end
opts.on('--with-github GITHUB_NAME', 'open file on github in html format') do |github_name|
options['with-github'] = true
options['github-name'] = github_name
end
opts.on('--last-commit-id COMMIT_ID', 'last commit id') do |commit_id|
options['last-commit-id'] = commit_id
end
opts.on('--with-hg', 'display hg commit and username, only support html format') do
options['with-hg'] = true
end
opts.on('--with-git', 'display git commit and username, only support html format') do
options['with-git'] = true
end
opts.on('--template TEMPLATE', 'customize erb template') do |template|
options['template'] = template
end
opts.on('--output-file OUTPUT_FILE', 'output html file for the analyzing result') do |output_file|
options['output-file'] = output_file
end
opts.on('--silent', 'silent mode') do
options['silent'] = true
end
%w[vendor spec test features].each do |pattern|
opts.on("--#{pattern}", "include #{pattern} files") do
options[pattern] = true
end
end
opts.on_tail('-v', '--version', 'Show this version') do
require 'rails_best_practices/version'
puts RailsBestPractices::VERSION
exit
end
opts.on_tail('-h', '--help', 'Show this message') do
puts opts
exit
end
opts.on(
'-x',
'--exclude PATTERNS',
"Don't analyze files matching a pattern",
'(comma-separated regexp list)'
) do |list|
begin
options['exclude'] = list.split(',').map { |x| Regexp.new x }
rescue RegexpError => e
raise OptionParser::InvalidArgument, e.message
end
end
opts.on(
'-o',
'--only PATTERNS',
'Analyze files only matching a pattern',
'(comma-separated regexp list)'
) do |list|
begin
options['only'] = list.split(',').map { |x| Regexp.new x }
rescue RegexpError => e
raise OptionParser::InvalidArgument, e.message
end
end
opts.on('-g', '--generate', 'Generate configuration yaml') do
options['generate'] = true
end
opts.on(
'-c',
'--config CONFIG_PATH',
'configuration file location (defaults to config/rails_best_practices.yml)'
) do |config_path|
options['config'] = config_path
end
opts.parse!
end
options
end
end
end
| ruby | MIT | 2ef40880d12ff8ed5f516871133ec569df03b192 | 2026-01-04T15:47:01.660067Z | false |
flyerhzm/rails_best_practices | https://github.com/flyerhzm/rails_best_practices/blob/2ef40880d12ff8ed5f516871133ec569df03b192/lib/rails_best_practices/analyzer.rb | lib/rails_best_practices/analyzer.rb | # frozen_string_literal: true
require 'fileutils'
require 'json'
require 'ruby-progressbar'
module RailsBestPractices
# RailsBestPractices Analyzer helps you to analyze your rails code, according to best practices on https://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.
class Analyzer
attr_accessor :runner
attr_reader :path
DEFAULT_CONFIG = File.join(File.dirname(__FILE__), '..', '..', 'rails_best_practices.yml')
GITHUB_URL = 'https://github.com/'
# initialize
#
# @param [String] path where to generate the configuration yaml file
# @param [Hash] options
def initialize(path, options = {})
@path = File.expand_path(path || '.')
@options = options
@options['exclude'] ||= []
@options['only'] ||= []
end
# generate configuration yaml file.
def generate
FileUtils.cp DEFAULT_CONFIG, File.join(@path, 'config/rails_best_practices.yml')
end
# Analyze 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.
#
# @param [String] path the directory of rails project
# @param [Hash] options
def analyze
Core::Runner.base_path = @path
Core::Runner.config_path = @options['config']
@runner = Core::Runner.new
analyze_source_codes
analyze_vcs
end
# Output the analyze result.
def output
case @options['format']
when 'html'
@options['output-file'] ||= 'rails_best_practices_output.html'
output_html_errors
when 'json'
@options['output-file'] ||= 'rails_best_practices_output.json'
output_json_errors
when 'yaml'
@options['output-file'] ||= 'rails_best_practices_output.yaml'
output_yaml_errors
when 'xml'
@options['output-file'] ||= 'rails_best_practices_output.xml'
output_xml_errors
else
output_terminal_errors
end
end
# process lexical, prepare or reivew.
#
# get all files for the process, analyze each file,
# and increment progress bar unless debug.
#
# @param [String] process the process name, lexical, prepare or review.
def process(process)
parse_files.each do |file|
begin
puts file if @options['debug']
@runner.send(process, file, File.read(file))
rescue StandardError
if @options['debug']
warning = "#{file} looks like it's not a valid Ruby file. Skipping..."
plain_output(warning, 'red')
end
end
@bar.increment if display_bar?
end
@runner.send("after_#{process}")
end
# get all files for parsing.
#
# @return [Array] all files for parsing
def parse_files
@parse_files ||=
begin
files = expand_dirs_to_files(@path)
files = file_sort(files)
if @options['only'].present?
files = file_accept(files, @options['only'])
end
# By default, tmp, vender, spec, test, features are ignored.
%w[vendor spec test features tmp].each do |dir|
files = file_ignore(files, File.join(@path, dir)) unless @options[dir]
end
# Exclude files based on exclude regexes if the option is set.
@options['exclude'].each do |pattern|
files = file_ignore(files, pattern)
end
%w[Capfile Gemfile Gemfile.lock].each do |file|
files.unshift File.join(@path, file)
end
files.compact
end
end
# expand all files with extenstion rb, erb, haml, slim, builder and rxml under the dirs
#
# @param [Array] dirs what directories to expand
# @return [Array] all files expanded
def expand_dirs_to_files(*dirs)
extensions = %w[rb erb rake rhtml haml slim builder rxml rabl]
dirs.flatten.map do |entry|
next unless File.exist? entry
if File.directory? entry
Dir[File.join(entry, '**', "*.{#{extensions.join(',')}}")]
else
entry
end
end.flatten
end
# sort files, models first, mailers, helpers, and then sort other files by characters.
#
# models and mailers first as for prepare process.
#
# @param [Array] files
# @return [Array] sorted files
def file_sort(files)
models = files.find_all { |file| file =~ Core::Check::MODEL_FILES }
mailers = files.find_all { |file| file =~ Core::Check::MAILER_FILES }
helpers = files.find_all { |file| file =~ Core::Check::HELPER_FILES }
others =
files.find_all do |file|
file !~ Core::Check::MAILER_FILES && file !~ Core::Check::MODEL_FILES && file !~ Core::Check::HELPER_FILES
end
models + mailers + helpers + others
end
# ignore specific files.
#
# @param [Array] files
# @param [Regexp] pattern files match the pattern will be ignored
# @return [Array] files that not match the pattern
def file_ignore(files, pattern)
files.reject { |file| file.index(pattern) }
end
# accept specific files.
#
# @param [Array] files
# @param [Regexp] patterns, files match any pattern will be accepted
def file_accept(files, patterns)
files.select { |file| patterns.any? { |pattern| file =~ pattern } }
end
# output errors on terminal.
def output_terminal_errors
errors.each { |error| plain_output(error.to_s, 'red') }
plain_output("\nPlease go to https://rails-bestpractices.com to see more useful Rails Best Practices.", 'green')
if errors.empty?
plain_output("\nNo warning found. Cool!", 'green')
else
plain_output("\nFound #{errors.size} warnings.", 'red')
end
end
# load hg commit and hg username info.
def load_hg_info
hg_progressbar = ProgressBar.create(title: 'Hg Info', total: errors.size) if display_bar?
errors.each do |error|
info_command = "cd #{@runner.class.base_path}"
info_command += " && hg blame -lvcu #{error.filename[@runner.class.base_path.size..-1].gsub(%r{^/}, '')}"
info_command += " | sed -n /:#{error.line_number.split(',').first}:/p"
hg_info = system(info_command)
unless hg_info == ''
hg_commit_username = hg_info.split(':')[0].strip
error.hg_username = hg_commit_username.split(/\ /)[0..-2].join(' ')
error.hg_commit = hg_commit_username.split(/\ /)[-1]
end
hg_progressbar.increment if display_bar?
end
hg_progressbar.finish if display_bar?
end
# load git commit and git username info.
def load_git_info
git_progressbar = ProgressBar.create(title: 'Git Info', total: errors.size) if display_bar?
start = @runner.class.base_path =~ %r{/$} ? @runner.class.base_path.size : @runner.class.base_path.size + 1
errors.each do |error|
info_command = "cd #{@runner.class.base_path}"
info_command += " && git blame -L #{error.line_number.split(',').first},+1 #{error.filename[start..-1]}"
git_info = system(info_command)
unless git_info == ''
git_commit, git_username = git_info.split(/\d{4}-\d{2}-\d{2}/).first.split('(')
error.git_commit = git_commit.split(' ').first.strip
error.git_username = git_username.strip
end
git_progressbar.increment if display_bar?
end
git_progressbar.finish if display_bar?
end
# output errors with html format.
def output_html_errors
require 'erubis'
template =
@options['template'] ?
File.read(File.expand_path(@options['template'])) :
File.read(File.join(File.dirname(__FILE__), '..', '..', 'assets', 'result.html.erb'))
if @options['with-github']
last_commit_id = @options['last-commit-id'] || `cd #{@runner.class.base_path} && git rev-parse HEAD`.chomp
unless @options['github-name'].start_with?('https')
@options['github-name'] = GITHUB_URL + @options['github-name']
end
end
File.open(@options['output-file'], 'w+') do |file|
eruby = Erubis::Eruby.new(template)
file.puts eruby.evaluate(
errors: errors,
error_types: error_types,
atom: @options['with-atom'],
textmate: @options['with-textmate'],
vscode: @options['with-vscode'],
sublime: @options['with-sublime'],
mvim: @options['with-mvim'],
github: @options['with-github'],
github_name: @options['github-name'],
last_commit_id: last_commit_id,
git: @options['with-git'],
hg: @options['with-hg']
)
end
end
def output_xml_errors
require 'rexml/document'
document =
REXML::Document.new.tap do |d|
d << REXML::XMLDecl.new
end
checkstyle = REXML::Element.new('checkstyle', document)
errors.group_by(&:filename).each do |file, group|
REXML::Element.new('file', checkstyle).tap do |f|
f.attributes['name'] = file
group.each do |error|
REXML::Element.new('error', f).tap do |e|
e.attributes['line'] = error.line_number
e.attributes['column'] = 0
e.attributes['severity'] = 'error'
e.attributes['message'] = error.message
e.attributes['source'] = 'com.puppycrawl.tools.checkstyle.' + error.type
end
end
end
end
formatter = REXML::Formatters::Default.new
File.open(@options['output-file'], 'w+') do |result|
formatter.write(document, result)
end
end
# output errors with yaml format.
def output_yaml_errors
File.open(@options['output-file'], 'w+') do |file|
file.write YAML.dump(errors)
end
end
# output errors with json format.
def output_json_errors
errors_as_hashes =
errors.map do |err|
{ filename: err.filename, line_number: err.line_number, message: err.message }
end
File.open(@options['output-file'], 'w+') do |file|
file.write JSON.dump(errors_as_hashes)
end
end
# plain output with color.
#
# @param [String] message to output
# @param [String] color
def plain_output(message, color)
if @options['without-color']
puts message
else
puts Colorize.send(color, message)
end
end
# analyze source codes.
def analyze_source_codes
@bar = ProgressBar.create(title: 'Source Code', total: parse_files.size * 4) if display_bar?
%w[lexical prepare review inline_disable].each { |process| send(:process, process) }
@bar.finish if display_bar?
end
# analyze version control system info.
def analyze_vcs
load_git_info if @options['with-git']
load_hg_info if @options['with-hg']
end
# if disaply progress bar.
def display_bar?
!@options['debug'] && !@options['silent']
end
# unique error types.
def error_types
errors.map(&:type).uniq
end
# delegate errors to runner
def errors
@runner.errors
end
end
end
| ruby | MIT | 2ef40880d12ff8ed5f516871133ec569df03b192 | 2026-01-04T15:47:01.660067Z | false |
flyerhzm/rails_best_practices | https://github.com/flyerhzm/rails_best_practices/blob/2ef40880d12ff8ed5f516871133ec569df03b192/lib/rails_best_practices/inline_disables.rb | lib/rails_best_practices/inline_disables.rb | # frozen_string_literal: true
require_rel 'inline_disables'
| ruby | MIT | 2ef40880d12ff8ed5f516871133ec569df03b192 | 2026-01-04T15:47:01.660067Z | false |
flyerhzm/rails_best_practices | https://github.com/flyerhzm/rails_best_practices/blob/2ef40880d12ff8ed5f516871133ec569df03b192/lib/rails_best_practices/lexicals.rb | lib/rails_best_practices/lexicals.rb | # frozen_string_literal: true
require_rel 'lexicals'
| ruby | MIT | 2ef40880d12ff8ed5f516871133ec569df03b192 | 2026-01-04T15:47:01.660067Z | false |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.