所以我跟着这个Balanced Payments tutorial,并尝试调整他们的付款模式以适合我的应用程序。
原件:
class Payment
def initialize(email, amount, credit_card_hash)
@email = email
@amount = (amount * 100).to_i
@credit_card_hash = credit_card_hash
@buyer = nil
@card = nil
@errors = []
end
end
我的简化版本(更新了完整模型的代码):
require 'balanced'
class Transaction < ActiveRecord::Base
attr_reader :errors, :amount
def initialize(amount)
@amount = (amount * 100).to_i
@buyer = nil
@card = nil
@errors = []
end
def charge
begin
find_or_create_buyer
debit_buyer
credit_owner
return true
rescue
return false
end
end
private
def find_or_create_buyer
begin
@buyer = current_user.balanced_customer
rescue
@errors << 'Your account is invalid'
end
end
def debit_buyer
begin
payment = @buyer.debit(@amount, "Test transaction")
rescue
@errors << 'Your credit card could not be charged'
end
end
def credit_owner
begin
Balanced::Marketplace.my_marketplace.owner_account.credit(amount)
rescue
@errors << 'Your credit card payment did not go through.'
end
end
end
问题是我每次尝试从rails控制台实例化类时都会遇到纯粹的ruby错误,
> payment = Transaction.new(0.01)
output error: #<NoMethodError: undefined method `has_key?' for nil:NilClass>
我用谷歌搜索过,但未能得到一个好的答案。
有什么想法吗?
答案 0 :(得分:2)
在活动记录初始化中,使用属性哈希来完成初始化程序
http://blog.hasmanythrough.com/2007/1/22/using-faux-accessors-to-initialize-values
答案 1 :(得分:1)
嗯,这似乎可以阻止错误,不管我到底做了什么。
不确定这是否会在以后出现任何问题,我们会看到。
def initialize(args = {})
super
@my_cache = {}
@amount = args[:amount]
@buyer = nil
@card = nil
@errors = []
end