-1

How would i go about including a method, defined in my helper, in my model. The model code is as follows:

class Statement
  attr_accessor :opening_balance, :closing_balance 

  def initialize(acct, year = nil, month = nil)
    @db = Database.instance
    @account    = acct
    @year       = year
    @month      = month
    @month_name = Date::MONTHNAMES[@month]
  end

  def to_s
    "#{@account.number}-#{@month_name}-#{@year}"
  end

  def to_pdf
    title = @account.name
    subtitle = "Account Statement: #{@month_name} #{@year}"
    # StatementPDF.new(title, subtitle, transactions).render
    StatementPDF.new(title, subtitle, transactions).render
  end
end

I wish to include the transactions method defined in my helper.

def transactions(account_id, start, finish)

  response = get_call('/Accounts/Statements/' + account_id.to_s + '/' + start + '/' + finish)
  response = JSON.parse(response.body)

  @transactions = response.map do |txn| 
    Transaction.new(txn)
  end

  return @transactions

end

I was looking at the following solutions (Rails 3 View helper method in Model) but don't know how to integrate it with my code.

Community
  • 1
  • 1
user3385136
  • 513
  • 1
  • 7
  • 20

1 Answers1

0

Just include the module in which your transactions method is defined, like this:

class Statement
  include NameOfTransactionModule

  attr_accessor :opening_balance, :closing_balance

  def initialize(acct, year = nil, month = nil)
    @db = Database.instance
    @account    = acct
    @year       = year
    @month      = month
    @month_name = Date::MONTHNAMES[@month]
  end

  def to_s
    "#{@account.number}-#{@month_name}-#{@year}"
  end

  def to_pdf
    title = @account.name
    subtitle = "Account Statement: #{@month_name} #{@year}"
    # StatementPDF.new(title, subtitle, transactions).render
    StatementPDF.new(title, subtitle, transactions).render
  end
end

This will make transactions method available as an instance method for the objects of Statement class.

K M Rakibul Islam
  • 33,760
  • 12
  • 89
  • 110
  • @K M Rakibul Islam I tried this by adding "include transactions" instead of "include NameOfTransactionModule". I am getting "undefined local variable or method `transactions' for Statement:Class" – user3385136 Sep 02 '15 at 09:06