client_side_validations icon indicating copy to clipboard operation
client_side_validations copied to clipboard

Feature request: Optionally require CSV's modules

Open mattboldt opened this issue 4 years ago • 0 comments

Hello! As mentioned in my comment here: https://github.com/DavyJonesLocker/client_side_validations/pull/795#issuecomment-691235835

I'm building some "Form Objects" serialized as json for use with client side schema libraries. As such, I do not need the entire CSV gem, so I've added it via gem 'client_side_validations', require: false

However, I noticed here that CSV is included in all instances of ActiveRecord, which I don't really need for my purposes. So as a workaround, I've created a CSVModelProxy class that includes them manually:

# Only include required modules from CSV for building JSON schema
require 'client_side_validations/config'
require 'client_side_validations/active_model'
class CSVModelProxy
  include ClientSideValidations::ActiveModel::Validations
  def initialize(original_model)
    @original_model = original_model
  end
  # Pass along all methods called by CSV (or anyone) to its original instance
  def method_missing(method_name, *args)
    @original_model.send(method_name, *args) || super
  end
end

This seems to work well (performance implications still TBD). But then, I noticed CSV also includes all its modules on all instances of ActiveModel::Validations and ActiveModel::Validator. Again this is overkill for my purposes, and I'd rather not introduce any complications into our ActiveModel::Model instances when I'm really just using CSV as a sort of serializer tool.

So it would be nice to have the option to only import some kind of wrapper class, e.g.

require 'client_side_validations/active_model_wrapper'
class FormObject
  def initialize(resource)
    @resource = ClientSideValidations::ActiveModelWrapper.new(resource)
    @validation_hash = @resource.client_side_validation_hash
  end
end

Would you be interested in a PR to achieve this?

mattboldt avatar Sep 17 '20 19:09 mattboldt