I am trying to compose an object Transaction
from objects TranFee
and Rate
.
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
The rate and TranFee objects are created from a hash like the one below.
reg_debit = {"name" => "reg_debit", "rate_base" => 0.0005,
"tran_fee" => 0.21, "rate_basis_points" => 0.002, "tran_auth_fee" => 0.10}
I am initializing the objects based on regex because the hash will eventually contain more values and I want the program to adjust as more items/classes are added.
Additionally there will be some instances where there are no key's starting with "tran". Does anyone know how to make Transaction
create only a Rate
object if TranFee
has no instance variables inside of it? (in otherwords, if the hash returns nothing when keys =~ /\Atran.*/
)
an example would be when the hash looks like this reg_debit = {"name" => "reg_debit", "rate_base" => 0.0005, "rate_basis_points" => 0.002}
, right now the output is
#<Transaction:0x007ff98c070548 @tranfee=#<PaymentType::TranFee:0x007ff98c070520>, @rate=#<PaymentType::Rate:0x007ff98c0704a8 @rate_base=0.0005, @rate_basis_points=0.002>>
So I am getting a TranFee
object with nothing in it and I would like for that to drop off in this situation. not sure if there may be a better way to design this? I was trying to think of a way to use ostruct or struct, but I havnt been able to figure it out. thanks for any help here.