From 48650ecf7e968f9bd36e422920d756fa39699676 Mon Sep 17 00:00:00 2001 From: Alexandre de Oliveira Date: Wed, 11 Mar 2015 14:53:57 -0300 Subject: [PATCH] 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. --- lib/active_model/serializer.rb | 3 +++ test/fixtures/poro.rb | 4 ++++ test/serializers/options_test.rb | 21 +++++++++++++++++++++ 3 files changed, 28 insertions(+) create mode 100644 test/serializers/options_test.rb diff --git a/lib/active_model/serializer.rb b/lib/active_model/serializer.rb index 6652ac44c..de380336d 100644 --- a/lib/active_model/serializer.rb +++ b/lib/active_model/serializer.rb @@ -140,6 +140,7 @@ def self.root_name def initialize(object, options = {}) @object = object + @options = options @root = options[:root] || (self.class._root ? self.class.root_name : false) @meta = options[:meta] @meta_key = options[:meta_key] @@ -201,6 +202,8 @@ def serializer_from_options(options) private + attr_reader :options + def self.get_serializer_for(klass) serializer_class_name = "#{klass.name}Serializer" serializer_class = serializer_class_name.safe_constantize diff --git a/test/fixtures/poro.rb b/test/fixtures/poro.rb index 4fcd13ac1..c42b48a3f 100644 --- a/test/fixtures/poro.rb +++ b/test/fixtures/poro.rb @@ -45,6 +45,10 @@ class ProfileSerializer < ActiveModel::Serializer attributes :name, :description urls :posts, :comments + + def arguments_passed_in? + options[:my_options] == :accessible + end end class ProfilePreviewSerializer < ActiveModel::Serializer diff --git a/test/serializers/options_test.rb b/test/serializers/options_test.rb new file mode 100644 index 000000000..9b25cc7fa --- /dev/null +++ b/test/serializers/options_test.rb @@ -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