Вопрос

I found that procs and lambdas can be used as a substitute for short methods and helper modules. I put methods that don't belong anywhere else into a file that is just a list of procs assigned to constants. For example, a file helper_procs.rb is required by init.rb, and contains the following:

RED_TEXT = proc{|t| "\e[31m#{t}\e[0m"} 
GREEN_TEXT = proc{|t| "\e[32m#{t}\e[0m"}
YELLOW_TEXT = proc{|t| "\e[33m#{t}\e[0m"}

CURRENT_TIME = proc do
  date = Time.now.to_s.split(' ')[0].split('-').reverse.join('-')
  time = Time.now.to_s.split(' ')[1]; "#{time} (#{date})"
end

and then, anywhere in the program (in a different file), I do:

puts GREEN_TEXT["A string!"]
puts CURRENT_TIME.call

Is it bad practice? Are there pitfalls?

Это было полезно?

Решение

That is a bad practice. Defining constants on the main level is as bad as using global variables. That defeats the purpose of object oriented programming (OOP). In OOP, you want to hide unnecessary things as much as possible. If something always works on a string, then that should not be accessible outside of the context of a string, and that should be defined on the String class. If something always provides some form of a time, then that should be defined on the Time class, either as a class or an instance method depending on the nature of the method.

Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top