Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Run a helper method on a model class method

I created a helper method that I want to run on a model class method and getting a method not found error.

lib/model_helper

module ModelHelper
  def method_i_want_to_use
    puts "I want to use this method"
  end
end

model/foo

    class Foo < ActiveRecord::Base
    include ModelHelper
    def self.bar
      method_i_want_to_use
    end
end

This setup gives me a no method error.

like image 557
xeroshogun Avatar asked May 05 '26 18:05

xeroshogun


1 Answers

You have to extend the module instead of include.

extend ModelHelper

include makes the methods available as instance methods of Foo. That means, you can call the method method_i_want_to_use on instances of Foo, not on Foo itself. If you want to call on Foo itself, then use extend.

module ModelHelper
  def method_i_want_to_use
    puts "I want to use this method"
  end
end

class Foo
  extend ModelHelper

  def self.bar
    method_i_want_to_use
  end
end

Foo.bar
# >> I want to use this method
like image 83
Arup Rakshit Avatar answered May 08 '26 12:05

Arup Rakshit