Search code examples
ruby-on-railsmigrationmonkeypatching

Why does null monkeypatch remove methods in migration but not in rails console?


This behavior is pretty cool because it makes it easy to write "futureproof" migrations where the migration defines the model class inline in case the class is later removed from the codebase. But how does it work?

$ rails c
pry(main)> User.methods.count
=> 686
pry(main)> class User < ActiveRecord::Base; end
=> nil
pry(main)> User.methods.count
=> 686

Here's a migration:

class FrobulateUsers < ActiveRecord::Migration
  puts User.methods.count

  class User < ActiveRecord::Base
  end

  puts User.methods.count
  ...
end

And when I run it:

$ rake db:migrate
687
666

How come the methods disappear in the migration but not in the console?


Solution

  • Messing around with this, this is the true class names...

    class FrobulateUsers < ActiveRecord::Migration
    
      puts User.name
    
      class User < ActiveRecord::Base
      end
    
      puts User.name
    
    end
    

    Output

    User
    FrobulateUsers::User
    

    A note, you can put this on the outside of the class...

    # 20150810221740_frobulate_users.rb
    
    class User < ActiveRecord::Base
    end
    
    class FrobulateUsers < ActiveRecord::Migration
    
      puts User.name
    
    end
    

    Output

    User