Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Writing macro for activerecord

I'm trying to write a new macro for my ActiveRecord model (User). Macro will be defined in my own gem which called Kart.

Below is my implementation for my gem Kart and User

kart.rb

require "kart/version"

module Kart
  extend ActiveSupport::Concern

  included do
    def goodbye
      p "Gooooood"
    end
  end
end

ActiveSupport.on_load :active_record do
  ActiveRecord::Base.send :include, Kart
end

user.rb

class User < ApplicationRecord
  goodbye # this is my macro, simply print "Goodbye"
end

For my understanding, when I run "rails c", "Gooooood" will be printed in the console but error message "method_missing': undefined local variable or methodgoodbye' for User" always shows up.

like image 219
Richard Tran Avatar asked Jun 17 '26 08:06

Richard Tran


1 Answers

There are 2 main problems that I finally figure out:

  • I need Railtie to integrate this gem with my rails app. You can find guidance in here: https://api.rubyonrails.org/classes/Rails/Railtie.html
  • I forgot to rebuild and run bundle update after fixing code in my gem (beginner error but stuck for almost one day)
like image 132
Richard Tran Avatar answered Jun 19 '26 23:06

Richard Tran



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!