From 7936e3efbaada219b64e20e9491537bff084c724 Mon Sep 17 00:00:00 2001 From: twinturbo Date: Sat, 14 Jul 2012 14:54:23 +0200 Subject: [PATCH] Add "scope" method --- README.markdown | 4 ++-- lib/active_model/serializer.rb | 7 ++++++- test/serializer_test.rb | 5 +++++ 3 files changed, 13 insertions(+), 3 deletions(-) diff --git a/README.markdown b/README.markdown index 94292668..5fab7d2d 100644 --- a/README.markdown +++ b/README.markdown @@ -126,12 +126,12 @@ class PostSerializer < ActiveModel::Serializer # only let the user see comments he created. def comments - post.comments.where(:created_by => options[:scope]) + post.comments.where(:created_by => scope) end end ``` -In a serializer, `options[:scope]` is the current authorization scope (usually +In a serializer, `scope` is the current authorization scope (usually `current_user`), which the controller gives to the serializer when you call `render :json` diff --git a/lib/active_model/serializer.rb b/lib/active_model/serializer.rb index 8c177581..b2eac4ee 100644 --- a/lib/active_model/serializer.rb +++ b/lib/active_model/serializer.rb @@ -103,7 +103,7 @@ module ActiveModel # end # # def author? - # post.author == options[:scope] + # post.author == scope # end # end # @@ -520,6 +520,11 @@ module ActiveModel hash end + # Returns options[:scope] + def scope + @options[:scope] + end + alias :read_attribute_for_serialization :send # Use ActiveSupport::Notifications to send events to external systems. diff --git a/test/serializer_test.rb b/test/serializer_test.rb index bdd20ae3..75c148b3 100644 --- a/test/serializer_test.rb +++ b/test/serializer_test.rb @@ -94,6 +94,11 @@ class SerializerTest < ActiveModel::TestCase has_many :comments, :serializer => CommentSerializer end + def test_scope_works_correct + serializer = ActiveModel::Serializer.new :foo, :scope => :bar + asser_equal serializer.scope, :bar + end + def test_attributes user = User.new user_serializer = DefaultUserSerializer.new(user, {})