calculator_controller.rb
来自「RubyonRailsC.zip ruby on rails的源码」· RB 代码 · 共 46 行
RB
46 行
class CalculatorController < ApplicationController
before_filter :set_charset
def set_charset
@headers["Content-Type"] = "text/html; charset=GB2312"
end
def calculate
if request.post?
@errors = []
arg1 = convert_float(:arg1)
arg2 = convert_float(:arg2)
op = convert_operator(:operator)
if @errors.empty?
begin
@result = op.call(arg1, arg2)
rescue Exception => err
@result = err.message
end
end
end
end
private
def convert_float(name)
if params[name].blank?
@errors << "#{name} 不能为空"
else
begin
Float(params[name])
rescue Exception => err
@errors << "#{name}: 无法将输入数据转换为float型"
nil
end
end
end
def convert_operator(name)
case params[name]
when "+" then proc {|a,b| a+b}
when "-" then proc {|a,b| a-b}
when "*" then proc {|a,b| a*b}
when "/" then proc {|a,b| a/b}
end
endend
⌨️ 快捷键说明
复制代码Ctrl + C
搜索代码Ctrl + F
全屏模式F11
增大字号Ctrl + =
减小字号Ctrl + -
显示快捷键?