TechnicallyTorion
TechnicallyTorion

Reputation: 27

Accessing helpers within the model in the controller

I am wondering why I have a helper method from a module I've mixed in with my model throwing the NoMethodError within my controller when I try to call that model's protected method. My code currently looks like this.

#models/my_class.rb

class MyClass
  include HelperModule
    
  def self.list_payments(payments)
     new_payments = []
     payments.each do |payment|
        payment = MyClass.new.tap do |p|
           p.quality_check = quality_check(payment)
           p.amount_with_fee = calculate_fees(payment)
        end

        if payment.valid?
          payment.save
          new_payments << payment
        end
     end
     new_payments
  end
end

 #controllers/my_classes_controller

 class MyClassController < ApplicationController
     def index
        response = Faraday.get
        unfiltered_payments = JSON.parse(response.body)["payments"]
        @payments = MyClass.list_payments(unfiltered_payments)
     end
 end

quality_check and calculate_fees are both within my helper module but in the controller when I call MyClass.list_payments(payments) I get the NoMethodError for both methods. I can get it to work by including the helpers within my controller and using this function as a private function within my controller, but I was trying to follow the fat model/skinny controller convention. Am I missing something here or am I okay with placing the helpers within the controller and moving this function to the controller? using ruby 2.6.3p62 (2019-04-16 revision 67580) [universal.x86_64-darwin20], and Rails 6.1.0

Upvotes: 1

Views: 551

Answers (1)

max pleaner
max pleaner

Reputation: 26758

It's because def self.list_payments is a class method but you are calling include HelperModule which only affects the instance method scope.

Quick fix, just replace include with extend.

Upvotes: 2

Related Questions