在模型中包含辅助方法

时间:2015-09-01 15:56:18

标签: ruby-on-rails

我如何在我的模型中包含我的助手中定义的方法。型号代码如下:

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

我希望包含我的助手中定义的交易方法。

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

我正在查看以下解决方案(Rails 3 View helper method in Model),但不知道如何将其与我的代码集成。

1 个答案:

答案 0 :(得分:0)

只需包含定义transactions方法的模块,如下所示:

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

这将使transactions方法可用作Statement类对象的实例方法。