1
0
Fork 0
mirror of https://github.com/paper-trail-gem/paper_trail.git synced 2022-11-09 11:33:19 -05:00
paper-trail-gem--paper_trail/lib/paper_trail/attribute_serializers/object_attribute.rb
Jared Beck ad3806fcbb An idea to combat model pollution
Problem
-------

`has_paper_trail` adds too many methods to the ActiveRecord model.

> If I'm counting correctly, installing the paper_trail gem adds 36 instance
> methods and 10 class methods to all of your active record models. Of those
> 46, 13 have a prefix, either "pt_" or "paper_trail_". I don't know what the
> best way to deal with this is. Ideally, we'd add far fewer methods to
> people's models. If we were able to add fewer methods to models, then I
> wouldn't mind prefixing all of them.
> https://github.com/airblade/paper_trail/issues/703

Solution
--------

Add only two methods to the AR model.

1. An instance method `#paper_trail`
2. A class method `.paper_trail`

The instance method would return a `RecordTrail` and the class method would
return a `ClassTrail`. Those names are totally up for debate.

Advantages
----------

- Plain ruby, easy to understand
- Adding new methods to e.g. the `RecordTrail` does not add any methods to
  the AR model.
- Methods privacy is more strongly enforced.
- Enables isolated testing of e.g. `RecordTrail`; it can be constructed with a
  mock AR instance.

Disadvantages
-------------

- Two new classes, though they are simple.
2016-06-06 01:18:31 -04:00

39 lines
1.1 KiB
Ruby

require "paper_trail/attribute_serializers/cast_attribute_serializer"
module PaperTrail
module AttributeSerializers
# Serialize or deserialize the `version.object` column.
class ObjectAttribute
def initialize(model_class)
@model_class = model_class
end
def serialize(attributes)
alter(attributes, :serialize)
end
def deserialize(attributes)
alter(attributes, :deserialize)
end
private
# Modifies `attributes` in place.
# TODO: Return a new hash instead.
def alter(attributes, serialization_method)
# Don't serialize before values before inserting into columns of type
# `JSON` on `PostgreSQL` databases.
return attributes if object_col_is_json?
serializer = CastAttributeSerializer.new(@model_class)
attributes.each do |key, value|
attributes[key] = serializer.send(serialization_method, key, value)
end
end
def object_col_is_json?
@model_class.paper_trail.version_class.object_col_is_json?
end
end
end
end