1
\$\begingroup\$

I just wonder whether it is a common approach to hit the third-party API and fetch values within the initialize method?

Ex.

    class BalanceTransaction::Update
      include Service

      attr_reader :offset, :transactions

      def initialize(offset)
        @offset = offset
        @transactions = fetch_transactions
      end

      def call
        transactions.auto_paging_each do |txn|
          type = txn[:type]
          source = txn[:source]

          case type
            when 'charge', 'adjustment' # NOTE: adjustment is something
              invoice = find_invoice(source)
              ac_id = invoice.ac.id
              update_attrs(id: invoice.id, account_id: ac_id, type:'invoice', attrs: txn)
            when 'refund'
              refund = find_refund(source)
              ac_id = refund.invoice.account.id
              update_attrs(id: refund.id, account_id: ac_id, type:'refund', attrs: txn)
          end
        end
      end

   private 
      def external_card_balance
        Stripe::BalanceTransaction
      end

      def fetch_transactions
       external_card_balance.all
      end
\$\endgroup\$
1
  • \$\begingroup\$ How is this class used, and what is in the included Service? \$\endgroup\$ Commented Feb 1, 2017 at 18:32

1 Answer 1

2
\$\begingroup\$

Since it seems you only need the transactions value once, you might as well just make an attribute reader that does the work:

  def transactions
    external_card_balance.all
  end

No real need to break in down into "fetch and store" and "read from store and iterate", when you can just say "fetch and iterate".

If you're going to be using the transactions collection multiple times, you can either memoize it:

  def transactions
    @transactions ||= external_card_balance.all
  end

Or you can simply pass the transactions as a constructor argument. The latter moves the responsibility for fetching transactions to the user of the class, rather than the class itself, which may make more sense - or it may not. Your call.

\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.