How to Force Activerecord to Reload a Class

How do I force ActiveRecord to reload a class?

The answer is yes!

Blog.reset_column_information

Rails 4.2: How to force to reload model definition?

@Mariah suggested you a way to reload an instance of a model class, but in case your intention was to really reload the definition of a class, you could do it with this trick:

before_action :reload_model

def reload_model
Object.send(:remove_const, :PaymentRequest)
load 'app/models/payment_request.rb'
end

Beware of side effects like impossibility to access a PaymentRequest from other parts of same instance of your application during that class is reloading. Actually I doubt if doing this in your controller code is a right thing.

Reloading a class may be useful when some constant value should be updated (as it is filled upon first class loading and changed during time). But in case this situation occurs during your application is live, you'd better consider changing constant-based solution to something more appropriate.

How to fully reload an ActiveRecord to reset it's memoized values?

The good way is the one you already have: Completely recreating the object.

You cannot "reload" the object's memoized values in any easy "Rails" way, as memoizing attributes isn't a function of Rails or ActiveRecord. Neither knows anything about how you're memoizing methods.

how to force a Rails model to get a new version in a callback

Calling reload affects attributes only. If you want to reload an association, you need to call reload on the association directly.

<association>.reload

Reload column names in ActiveRecord model class

Legislator.reset_column_information (API info)

Refresh class instance variable that is set with ||=

How can one go about "refreshing" the instance variable?

Simply set it to nil. Then, upon next call, it'll be reloaded from the db.

Or you could proactively replace the value yourself. First, separate memoization and computation.

def self.get_lastname(client_id)
@client_by_lastname ||= compute_client_by_last_name

end

def compute_client_by_last_name
Client.select(:id, :lastname)
.map{|e| e.attributes.values}
.inject({}){|memo, client| memo[client[0]] = client[1]; memo}
end

Then, when you want to refresh the state (in an after_save callback or wherever)

@client_by_lastname = compute_client_by_last_name

Rails, ActiveRecord: Callback run during #reload

You can override the reload method in your model:

def reload
super

# code with whatever you need to clean, for example:
@processed_records = nil
end

How can I get Rails development server to reload my class upon changes?

  1. Don't use require. That's only for 3rd party libraries.
  2. Change filename to snake_case.rb. Rails will pick up changes automatically.


Related Topics



Leave a reply



Submit