Ccyan
Ccyan

Reputation: 1057

Override ActiveSupport::Concern in model

I have a concern that looks like this:

module Foo
  extend ActiveSupport::Concern

  def bar
    puts "bar"
  end
end

Three other models use that class methods since they need to the same thing. Then I have a one-off model that needs the method to do something else. I have the set up like this:

class FooFoo < ApplicationRecord
  def self.bar
    puts "foo bar"
  end
end

Now, when I call FooFoo.bar, it would print "foo" instead of "foo bar". How do I override the method defined in the concern? I want it to only run the method defined in my model, FooFoo, and not the one in the concern, Foo. I looked all over but I don't think I saw what I needed. some help would be greatly appreciated!

EDIT: I also tried this hoping it would work but it didn't:

class FooFoo < ApplicationRecord
  def FooFoo.bar # I used FooFoo.bar here instead of self.bar
    puts "foo bar"
  end
end

Upvotes: 0

Views: 462

Answers (1)

Mark Merritt
Mark Merritt

Reputation: 2695

The problem is that you need to explicitly state that you want bar to be a class method...

module Foo
  extend ActiveSupport::Concern

  class_methods do 
    def bar
      puts "bar"
    end
  end
end

Now, you can override it...

class FooFoo < ApplicationRecord
  def self.bar
    puts "foo bar"
  end
end

Upvotes: 1

Related Questions