mirror of
https://github.com/ditkrg/active_model_serializers.git
synced 2026-01-24 23:06:50 +00:00
Add "scope" method
This commit is contained in:
parent
3e87c6414d
commit
7936e3efba
@ -126,12 +126,12 @@ class PostSerializer < ActiveModel::Serializer
|
|||||||
|
|
||||||
# only let the user see comments he created.
|
# only let the user see comments he created.
|
||||||
def comments
|
def comments
|
||||||
post.comments.where(:created_by => options[:scope])
|
post.comments.where(:created_by => scope)
|
||||||
end
|
end
|
||||||
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
|
`current_user`), which the controller gives to the serializer when you call
|
||||||
`render :json`
|
`render :json`
|
||||||
|
|
||||||
|
|||||||
@ -103,7 +103,7 @@ module ActiveModel
|
|||||||
# end
|
# end
|
||||||
#
|
#
|
||||||
# def author?
|
# def author?
|
||||||
# post.author == options[:scope]
|
# post.author == scope
|
||||||
# end
|
# end
|
||||||
# end
|
# end
|
||||||
#
|
#
|
||||||
@ -520,6 +520,11 @@ module ActiveModel
|
|||||||
hash
|
hash
|
||||||
end
|
end
|
||||||
|
|
||||||
|
# Returns options[:scope]
|
||||||
|
def scope
|
||||||
|
@options[:scope]
|
||||||
|
end
|
||||||
|
|
||||||
alias :read_attribute_for_serialization :send
|
alias :read_attribute_for_serialization :send
|
||||||
|
|
||||||
# Use ActiveSupport::Notifications to send events to external systems.
|
# Use ActiveSupport::Notifications to send events to external systems.
|
||||||
|
|||||||
@ -94,6 +94,11 @@ class SerializerTest < ActiveModel::TestCase
|
|||||||
has_many :comments, :serializer => CommentSerializer
|
has_many :comments, :serializer => CommentSerializer
|
||||||
end
|
end
|
||||||
|
|
||||||
|
def test_scope_works_correct
|
||||||
|
serializer = ActiveModel::Serializer.new :foo, :scope => :bar
|
||||||
|
asser_equal serializer.scope, :bar
|
||||||
|
end
|
||||||
|
|
||||||
def test_attributes
|
def test_attributes
|
||||||
user = User.new
|
user = User.new
|
||||||
user_serializer = DefaultUserSerializer.new(user, {})
|
user_serializer = DefaultUserSerializer.new(user, {})
|
||||||
|
|||||||
Loading…
Reference in New Issue
Block a user