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?
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_royalty that takes two arguments. Then, a couple of lines after the inclusion of that module you use class macro attr_accessor which defines two methods,
def book_royalty
@book_royalty
end
def book_royalty= val
@book_royalty = val
end
This effectively overwrites your book_royalty from the module. Now it accepts no arguments. Hence the error
wrong number of arguments (2 for 0)
when trying to execute line
book.book_royalty("enddate", basis)
You don't need attr_accessor or anything else in order to use a method from included module. It becomes available automatically.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With