Ruby on Rails Monkey Patching a Gem's Model

Viewed 5035

This might be silly, but I'm including a gem which represents all the models I need for my project. I want to add a method, to_custom_string to one of those models, Person.

I was attempting to do this via (following this example): config/initializers/extensions/person.rb

Which contained something like:

class Person < ActiveRecord::Base
  def to_custom_string
    address.street.to_s
  end
end

The Person class in the gem has a has_one :address association.

The problem I was experiencing was that this patch seems to override the Person class from the gem, instead of patching it. What's crazy is that this override behavior was only experienced via rake (all of the associations declared in the Person class from the gem are lost).

My rake task was something like:

namespace :convert
  task :all_persons => :environment do
    Person.where(:param => value).includes(:address).find_in_batches(:batch_size => 2000) do |persons|
      persons.each do |person|
        puts person.to_custom_string
      end
    end
  end
end

calling bundle exec rake convert:all_persons gave me:

Association named 'address' was not found; perhaps you misspelled it?

But copying and pasting the code in the rake task into rails console worked fine.

My current solution is to copy the code for Person from the gem into my app/models directory, and have my to_custom_string method there, which I know is wrong.

Can someone please explain why a) irb preserved my Person associations, but rake did not, and b) how I can get rake to cooperate?

Thank you!

2 Answers
Related