我想从对象TranFee
和Rate
组成对象Transaction
。撰写对象,而不初始化不在散列的对象
class Transaction
attr_reader :tranfee, :rate
def initialize(hash)
@tranfee = PaymentType::TranFee.new(hash)
@rate = PaymentType::Rate.new(hash)
end
end
module PaymentType
def initialize(args = {}, regex)
args.each do |key,value|
if key =~ regex
instance_variable_set("@#{key}", value) unless value.nil?
eigenclass = class << self; self; end
eigenclass.class_eval do
attr_reader key
end
end
end
end
class TranFee
include PaymentType
def initialize(args, regex = /\Atran.*/)
super(args, regex)
end
end
class Rate
include PaymentType
def initialize(args, regex = /\Arate.*/)
super(args, regex)
end
end
end
Rate和TranFee对象是从像下面这样的散列创建的。
reg_debit = {"name" => "reg_debit", "rate_base" => 0.0005,
"tran_fee" => 0.21, "rate_basis_points" => 0.002, "tran_auth_fee" => 0.10}
我初始化基于正则表达式的对象,因为哈希最终将包含更多的价值,我想程序调整为更多的项目/添加类。
此外,还有一些情况下没有密钥以“tran”开头。有没有人知道如何使Transaction
只创建一个Rate
对象如果TranFee
里面没有实例变量?
当哈希看起来像这样reg_debit = {"name" => "reg_debit", "rate_base" => 0.0005, "rate_basis_points" => 0.002}
一个例子是,现在的产量是
#<Transaction:0x007ff98c070548 @tranfee=#<PaymentType::TranFee:0x007ff98c070520>, @rate=#<PaymentType::Rate:0x007ff98c0704a8 @rate_base=0.0005, @rate_basis_points=0.002>>
所以我得到一个TranFee
对象包含任何东西(。换句话说,如果当keys =~ /\Atran.*/
哈希没有返回)它和我想在这种情况下下降。不知道是否有更好的方法来设计这个?我试图想出一种使用ostruct或struct的方法,但我很想弄明白。感谢您的帮助。
好点。你可能会考虑'root_key,_child_key = k.partition('_')'代替正则表达式。 – 2014-11-24 16:06:00