lib/ach/file.rb in ach_builder-0.0.2 vs lib/ach/file.rb in ach_builder-0.2.1

- old
+ new

@@ -1,50 +1,56 @@ module ACH + # An ACH::File instance represents an actual ACH file. Every file has an + # ACH::File::Header and ACH::File::Control records and a variable number of + # ACH::Batches. The ACH::File::TransmissionHeader is optional. (Refer to the + # target financial institution's documentation.) + # + # == Example + # + # # Subclass ACH::File to set default values: + # class CustomAchFile < ACH::File + # immediate_dest '123123123' + # immediate_dest_name 'COMMERCE BANK' + # immediate_origin '123123123' + # immediate_origin_name 'MYCOMPANY' + # end + # + # # Create a new instance: + # ach_file = CustomAchFile.new do + # batch(:entry_class_code => "WEB", :company_entry_descr => "TV-TELCOM") do + # effective_date Time.now.strftime('%y%m%d') + # desc_date Time.now.strftime('%b %d').upcase + # origin_dfi_id "00000000" + # entry :customer_name => 'JOHN SMITH', + # :customer_acct => '61242882282', + # :amount => '2501', + # :routing_number => '010010101', + # :bank_account => '103030030' + # end + # end + # + # # convert to string + # ach_file.to_s! # => returns string representation of file + # + # # write to file + # ach_file.write('custom_ach.txt') class File < Component - has_many :batches, lambda{ {:batch_number => batches.length + 1} } - - def batch_count - batches.length - end - - def block_count - (file_entry_count.to_f / BLOCKING_FACTOR).ceil - end - - def file_entry_count - batches.map{ |b| b.entries.length }.inject(&:+) || 0 - end - - def entry_hash - batches.map(&:entry_hash).compact.inject(&:+) - end - - def total_debit_amount - batches.map(&:total_debit_amount).compact.inject(&:+) - end - - def total_credit_amount - batches.map(&:total_credit_amount).compact.inject(&:+) - end - - def to_ach - extra = block_count * BLOCKING_FACTOR - file_entry_count - tail = ([Tail.new] * extra).unshift(control) - [header] + batches.map(&:to_ach).flatten + tail - end - - def to_s! - to_ach.map(&:to_s!).join("\r\n") + "\r\n" - end - - def record_count - 2 + batches.length * 2 + file_entry_count - end - - def write filename - return false unless valid? - ::File.open(filename, 'w') do |fh| - fh.write(to_s!) + autoload :Builder + autoload :Control + autoload :Header + autoload :TransmissionHeader + autoload :Reader + + include Builder + include TransmissionHeader + + has_many :batches, :proc_defaults => lambda{ {:batch_number => batches.length + 1} } + + # Opens a +filename+ and passes it's handler to the ACH::Reader object, which uses it as + # enum to scan for ACH contents line by line. + def self.read(filename) + ::File.open(filename) do |fh| + Reader.new(fh).to_ach end end end end