Ruby: How do I include methods from a Module into a subclass of ActiveModel::Serializer -
i'm trying include method helper module activemodel::serializer
subclass reason method not showing up.
here's simple helper module:
module helpers module serialisers def enforce_zulu_time(attribute) define_method(attribute) object.send(attribute).utc.iso8601 unless object.try(attribute).nil? end end end end
and here's test serialiser
class testserialiser < activemodel::serializer include helpers::serialisers attributes :updated_at enforce_zulu_time :updated_at end
and simple object serialise
class testitem include activemodel::serializersupport attr_reader :updated_at def initialize @updated_at = time.now.utc end end
and test
describe helpers::serialisers let(:item) { testitem.new } let(:serialiser) { testserialiser.new(item) } subject { serialiser.attributes } { expect(subject[:updated_at]).to be_zulu_time} end
results in
`<class:testserialiser>': undefined method `enforce_zulu_time' testserialiser:class (nomethoderror)
however if in testserialiser
instead
class testserialiser < activemodel::serializer attributes :updated_at ['updated_at'].each |attribute| define_method(attribute) object.send(attribute).utc.iso8601 unless object.send(attribute).blank? end end end
it works fine.
why enforce_zulu_time
method not being included?
replace include helpers::serialisers
extend helpers::serialisers
since expect class methods.
another solution use activesupport::concern
, see doc
sidenote
in order have code flexible free, recommend create own base class serializers, like:
class baseserializer < activemodel::serializer end
then have serializers inherit it. way can add features easily.
Comments
Post a Comment