mirror of
https://github.com/ditkrg/active_model_serializers.git
synced 2026-01-23 06:16:50 +00:00
Makes passed in options accessible inside serializers
In some cases, we want to pass arguments from the controller and we want to serializer a resource according to that. This allows serializers to use the `options` method to retrieve whatever was passed in via arguments.
This commit is contained in:
parent
b8df4b57a1
commit
48650ecf7e
@ -140,6 +140,7 @@ module ActiveModel
|
|||||||
|
|
||||||
def initialize(object, options = {})
|
def initialize(object, options = {})
|
||||||
@object = object
|
@object = object
|
||||||
|
@options = options
|
||||||
@root = options[:root] || (self.class._root ? self.class.root_name : false)
|
@root = options[:root] || (self.class._root ? self.class.root_name : false)
|
||||||
@meta = options[:meta]
|
@meta = options[:meta]
|
||||||
@meta_key = options[:meta_key]
|
@meta_key = options[:meta_key]
|
||||||
@ -201,6 +202,8 @@ module ActiveModel
|
|||||||
|
|
||||||
private
|
private
|
||||||
|
|
||||||
|
attr_reader :options
|
||||||
|
|
||||||
def self.get_serializer_for(klass)
|
def self.get_serializer_for(klass)
|
||||||
serializer_class_name = "#{klass.name}Serializer"
|
serializer_class_name = "#{klass.name}Serializer"
|
||||||
serializer_class = serializer_class_name.safe_constantize
|
serializer_class = serializer_class_name.safe_constantize
|
||||||
|
|||||||
4
test/fixtures/poro.rb
vendored
4
test/fixtures/poro.rb
vendored
@ -45,6 +45,10 @@ class ProfileSerializer < ActiveModel::Serializer
|
|||||||
attributes :name, :description
|
attributes :name, :description
|
||||||
|
|
||||||
urls :posts, :comments
|
urls :posts, :comments
|
||||||
|
|
||||||
|
def arguments_passed_in?
|
||||||
|
options[:my_options] == :accessible
|
||||||
|
end
|
||||||
end
|
end
|
||||||
|
|
||||||
class ProfilePreviewSerializer < ActiveModel::Serializer
|
class ProfilePreviewSerializer < ActiveModel::Serializer
|
||||||
|
|||||||
21
test/serializers/options_test.rb
Normal file
21
test/serializers/options_test.rb
Normal file
@ -0,0 +1,21 @@
|
|||||||
|
require 'test_helper'
|
||||||
|
|
||||||
|
module ActiveModel
|
||||||
|
class Serializer
|
||||||
|
class OptionsTest < Minitest::Test
|
||||||
|
def setup
|
||||||
|
@profile = Profile.new(name: 'Name 1', description: 'Description 1')
|
||||||
|
end
|
||||||
|
|
||||||
|
def test_options_are_accessible
|
||||||
|
@profile_serializer = ProfileSerializer.new(@profile, my_options: :accessible)
|
||||||
|
assert @profile_serializer.arguments_passed_in?
|
||||||
|
end
|
||||||
|
|
||||||
|
def test_no_option_is_passed_in
|
||||||
|
@profile_serializer = ProfileSerializer.new(@profile)
|
||||||
|
refute @profile_serializer.arguments_passed_in?
|
||||||
|
end
|
||||||
|
end
|
||||||
|
end
|
||||||
|
end
|
||||||
Loading…
Reference in New Issue
Block a user