How to remove validation using instance_eval clause in Rails?

后端 未结 18 2044
情话喂你
情话喂你 2021-02-01 02:11

I would like to enhance existing class using instance_eval. There original definition contains validation, which require presence of certain fields, ie:

class Du         


        
18条回答
  •  青春惊慌失措
    2021-02-01 02:51

    Assuming the original implementation of Dummy is defined in an engine there is a nasty hack that will do what you want. Define Dummy in your application to keep the original implementation of Dummy from being auto-loaded. Then load the source to Dummy and remove the line that does the validation. Eval the modified source.

    Put the following in your app/models/dummy.rb

    class Dummy < ActiveRecord::Base
    end
    
    # Replace DummyPlugin with name of engine
    engine = Rails::Application::Railties.engines.find { |e| e.class == DummyPlugin::Engine }
    dummy_source = File.read File.join(engine.config.root, "app", "models", "dummy.rb")
    dummy_source = dummy_source.gsub(/validates :field, :presence => true.*/, "")
    eval dummy_source
    

    If it is regular gem instead of an engine the same concept would apply, just would need to load the source for Dummy from the gem root instead of the engine root.

提交回复
热议问题