Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rails Active Model Serializer Include Concerns

Is it possible to include code in a serializer? I have some commonly used methods that I'd like to just include instead of always repeating them.

like image 893
Dan Avatar asked Dec 24 '22 19:12

Dan


2 Answers

If you are looking for some code as an example:

1) Create your specialized serializer that will include the specialized concern

# app/serializers/specialized_serializer.rb

class SpecializedSerializer < DefaultSerializer
  include SpecializedConcern
  ...
end

2) Create your specialized concern in a new concern folder

# app/serializers/concerns/specialized_concern.rb

module SpecializedConcern
  extend ActiveSupport::Concern

  included do
    include SomeModule
    ...
  end

  def some_method
    ...
  end
end

3) Add your new serialized concerns folder to your applications autoloaded path

# config/application.rb
...
config.autoload_paths += "#{config.root}/app/serializers/concerns"
...
like image 121
peoplespete Avatar answered Feb 01 '23 22:02

peoplespete


Absolutely, you can. Either use concern, ApplicationSerializer, or compose another classes for sharing behavior should be okay.

like image 33
Samnang Avatar answered Feb 01 '23 22:02

Samnang