MoskitoHero / barley

Barley is a fast and efficient ActiveModel serializer
MIT License
80 stars 3 forks source link

Add with_context class method to the serializer #3

Closed MoskitoHero closed 5 months ago

MoskitoHero commented 5 months ago

Description

This PR adds a with_context method to the Barley::Serializer class.

This allows you to use context in your serializer:

attribute :name do
  "#{object.name[context.locale]}" # Will use the locale from the context
end

So that when you can do

serializer.with_context(current_user: current_user, locale: I18n.locale)
# => #<Barley::Serializer:0x00007f8f3b8b3e08 @object=#<Product id: 1, name: "Product 1">, @context=#<struct current_user=1, locale=:en>>

And you get access to current_user and locale with the context.* shorthands.

Type of change

Please delete options that are not relevant.

How Has This Been Tested?

Added a test in SerializerTest

Checklist: