Adding a Method to the Rails ActiveRecord Class

In plain Ruby, this works just fine:

class TestSuper
  def foo
    puts "In TestSuper.foo"
  end
end

class TestClass < TestSuper
  def foo
    super
    puts "In TestClass.bar"
  end
end

class TestClass
  def bar
    puts "In TestClass.bar, second definition"
    puts "Calling foo:"
    foo
  end
end

t = TestClass.new
t.foo
t.bar

I can call foo () and bar () on the TestClass instance and get exactly what I expect:

In TestSuper.foo
In TestClass.bar
In TestClass.bar, second definition
Calling foo:
In TestSuper.foo
In TestClass.bar

However, when I try something very similar in Rails migration, I get errors:

#### my_model.rb ####
puts "In my_model.rb"
class MyModel
  has_many :foo
end

#### my_migration.rb ####
puts "In my_migration.rb"
class MyModel
  def bar
    foo.each{ |f| f.baz }
  end
end

class MyMigration < ActiveRecord::Migration
  def self.up
    MyModel.find(1).bar        
  end

  def self.down
    # Not applicable
  end
end

The first problem is that MyModel.find () disappears unless I explicitly extend ActiveRecord in my_migration.rb. Otherwise, it removes the superclass.

If I do this, I get an error when called fooin MyModel.bar ().

If I comment on the class definition (re) in my_migration.rb, find () and bar () work fine.

puts, , . , my_model.rb , MyModel ( my_migration.rb).

: Rails ?

+3
3

№ 2:

require 'app/models/my_model'
+4

, . . :

MyModel
class MyModel
  def bar
    foo.each{ |f| f.baz }
  end
end
MyModel.module_eval do
  def bar
    foo.each{ |f| f.baz }
  end
end
MyModel.send :include, Module.new {
  def bar
    foo.each{ |f| f.baz }
  end
}
+2

, ,

< ActiveRecord::Base

.

< ActiveRecord::Base

two class definitions must match

+1
source

Source: https://habr.com/ru/post/1781315/


All Articles