Exception
66 | Chapter 2: ActiveSupport and RailTies
sum {|x| (x-m)**2} / length
end
def standard_deviation
variance ** 0.5
end
end
"%.2f" % [1,2,3,4,5].standard_deviation # => "1.41"
Exception core_ext/exception.rb
Four methods are added toException for more intuitive stack traces:
- clean_messageruns the exception message throughPathname.clean_within, which
cleans any pathnames contained within the message (removes extra slashes and
resolves. and.. paths). - clean_backtraceruns the entire backtrace throughException::TraceSubstitutionsand
Pathname.clean_within, to clean the pathnames.TraceSubstitutionsis used by Action-
View’s templates to hide certain unsightly parts of the backtrace when template com-
pilation fails. - application_backtracereturns the set of frames belonging to the Rails application,
excluding those that are part of the Rails framework. - framework_backtracereturns the set of frames that are part of the Rails framework.
Together withapplication_backtrace, this is used on the default Rails rescue pages in
the development environment.
File core_ext/file.rb
File.atomic_writeatomically writes to a file; it creates a temporary file, yields it to a block
for writing, and then renames it to the destination. The advantage over a standard write is
that the destination file does not exist in a half-written state at any point.
File.atomic_write('important_file') do |important_file|
important_file.write data
end
Float core_ext/float.rb
Float#round rounds a floating-point number to the specified decimal place:
Math::PI # => 3.14159265358979
Math::PI.round # => 3
Math::PI.round(1) # => 3.1
Math::PI.round(2) # => 3.14
Math::PI.round(3) # => 3.142