I am trying to move some model code to a module.
The original model method:
I am trying to move some model code to a module.
The 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 a module:
module Calculation
def book_royalty(period='enddate', basis="Net receipts")
#stuff
end
end
But now I’m getting
wrong number of arguments (2 for 0)
This is the error I also get if I make the method in the book.rb model a class method i.e. if I make the method name self.book_royalty(args).
Am I inadvertently making the methods moved to the module class methods? I’m using include in book.rb, not extend. How can I get the parent model to successfully include the module’s methods?
Edit
book_royalty is 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
Explanation:
Your module defines a method
book_royaltythat takes two arguments. Then, a couple of lines after the inclusion of that module you use class macroattr_accessorwhich defines two methods,This effectively overwrites your
book_royaltyfrom the module. Now it accepts no arguments. Hence the errorwhen trying to execute line
You don’t need
attr_accessoror anything else in order to use a method from included module. It becomes available automatically.