【发布时间】:2015-08-05 15:23:44
【问题描述】:
我需要将下面的单个文件代码分离成一个模型、视图、控制器 (MVC) ruby 程序,该程序可以在不使用 Rails 的情况下通过命令行中的ruby 命令运行(有关如何运行的说明这个程序来自irb,请查看我的RubyBank Github Repo 上的 README.md。
require_relative 'view'
class BankAccount
attr_accessor :name, :balance
def initialize(name, balance=0)
@name = name
@balance = balance
end
def show_balance(pin_access)
if pin_access == pin || pin_access == bank_manager
puts "\nYour current balance is: $#{@balance}"
else
puts pin_error_message
end
end
def withdraw(pin_access, amount)
if pin_access == pin
@balance -= amount
puts "'\nYou just withdrew $#{amount} from your account. \n\nYour remaining balance is: $#{@balance}\n\n"
else
puts pin_error_message
end
if @balance < 0
@balance += amount
return overdraft_protection
end
end
def deposit(pin_access, amount)
if pin_access == pin
@balance += amount
puts "\nYou just deposited $#{amount} into your account. \n\nYour remaining balance is: $#{@balance}"
else
puts pin_error_message
end
end
private
def pin
@pin = 1234
end
def bank_manager
@bank_manager = 4321
end
def pin_error_message
puts "Invalid PIN number. Try again."
end
def overdraft_protection
puts "\nYou have overdrafted your account. We cannot complete your withdrawl. Please deposit money before trying again. \n\nYour corrected balance is $#{@balance}"
end
end
我正在寻找一个好的起点或一个完成此类任务的一般方法。
【问题讨论】:
-
应用程序应该做什么?您的课程
BankAccount是 模型(减去文本输出,如果它不只是记录的话)。你现在需要的是某种View和一个Controller类,它将模型修改为View中的一个动作。您必须有一些规范,说明 a) 哪些操作必须是可能的,b) 您必须创建哪种视图(Web、控制台、桌面等),否则您将很难满足客户/教师的要求。 -
应用程序应该从命令行问候他们,提示他们注册一个帐户,然后允许他们存款、取款或显示他们当前的余额。
-
在这种情况下,应用程序是基于控制台的。您当前拥有“放置”的方法可以转换为不同的视图(或通用视图的不同方法)。您的控制器应该接受来自控制台的输入,根据需要调用模型的相关部分(例如,当有人注册时实例化
BankAccount.new,在被询问时调用存款等),并决定接下来要显示哪个视图。 -
“这个任务超出了我目前的技能范围;它让我感到困惑。”虽然这看起来很刻薄,但练习的重点是让你弄清楚这一点。学习并不总是那么容易;很多时候,当我们探索不同的方式来达到我们想去的地方时,我们会花几天的时间感到困惑,似乎没有取得任何进展。在我们学习了我们正在使用的语言的模式和来龙去脉之前,这就是编程可以做到的。我们应该足智多谋,并且想办法解决这个问题。我们不会死去,但我们会做出英勇的尝试。
-
SO 不适用于外包任务,但绝对有方向。下面我提供了一个我过去用来做你正在尝试的事情的宝石。还可以考虑在一个文件中要求 Rails gems,如 ActiveRecord 和其他文件来完成同样的事情。
标签: ruby model-view-controller