Model code for module: wrong number of arguments, class / instance method?

I am trying to move some model code into a module.

Original model method:

I am trying to move some model code into a module.

Original model method:

class Book < ActiveRecord::Base
  def book_royalty(period='enddate', basis="Net receipts")
    #stuff
  end
end

      

So I add

include Calculation   

      

and move the method to the module:

module Calculation
  def book_royalty(period='enddate', basis="Net receipts")
    #stuff
  end
end

      

But now I get

wrong number of arguments (2 for 0)

This is the error I get if I make a method in the book.rb model a class method, that is, if I create a method name self.book_royalty(args)

.

Am I inadvertently translating methods into methods of a module class? I am using include

in book.rb, not extend

. How can I get the parent model to include module methods successfully?

Edit

book_royalty

called in the Royaltystatement model.

book.rb:

attr_accessor :book_royalty

      

royaltystatement.rb:

def initialize_arrays
  @royalty  = []
  ...
end

def sum_at_book_level(contract)
  contract.books.where(:exclude_from_royalty_calc => false).each do |book| 
    book.book_royalty("enddate", basis)
    @royalty.push(book.book_royalty("enddate", basis))
    # etc
end

      

+3


source to share


1 answer


Explanation:

Your module defines a method book_royalty

that takes two arguments. Then, a couple of lines after enabling this module, you use the macro class attr_accessor

, which defines two methods,

def book_royalty
  @book_royalty
end

def book_royalty= val
  @book_royalty = val
end

      

This effectively overwrites yours book_royalty

from the module. It now takes no arguments. Hence the error



wrong number of arguments (2 for 0)

when trying to execute the line

book.book_royalty("enddate", basis)

      

You don't need attr_accessor

or anything else to use the method from the included module. It becomes available automatically.

+5


source







All Articles