mirror of
https://github.com/ditkrg/active_model_serializers.git
synced 2026-01-25 07:16:49 +00:00
Reference scope by same name as serialization scope
By default, the serialization scope uses current_user, and you can now reference the scope as "current_user" in the serializer. If you override the scope using "serialization_scope" in your controller, it will use that method name instead.
This commit is contained in:
67
test/serialization_scope_name_test.rb
Normal file
67
test/serialization_scope_name_test.rb
Normal file
@@ -0,0 +1,67 @@
|
||||
require 'test_helper'
|
||||
require 'pathname'
|
||||
|
||||
class DefaultScopeNameTest < ActionController::TestCase
|
||||
TestUser = Struct.new(:name, :admin)
|
||||
|
||||
class UserSerializer < ActiveModel::Serializer
|
||||
attributes :admin?
|
||||
def admin?
|
||||
current_user.admin
|
||||
end
|
||||
end
|
||||
|
||||
class UserTestController < ActionController::Base
|
||||
protect_from_forgery
|
||||
|
||||
before_filter { request.format = :json }
|
||||
|
||||
def current_user
|
||||
TestUser.new('Pete', false)
|
||||
end
|
||||
|
||||
def render_new_user
|
||||
respond_with TestUser.new('pete', false), :serializer => UserSerializer
|
||||
end
|
||||
end
|
||||
|
||||
tests UserTestController
|
||||
|
||||
def test_default_scope_name
|
||||
get :render_new_user
|
||||
assert_equal '{"user":{"admin":false}}', @response.body
|
||||
end
|
||||
end
|
||||
|
||||
class SerializationScopeNameTest < ActionController::TestCase
|
||||
TestUser = Struct.new(:name, :admin)
|
||||
|
||||
class AdminUserSerializer < ActiveModel::Serializer
|
||||
attributes :admin?
|
||||
def admin?
|
||||
current_admin.admin
|
||||
end
|
||||
end
|
||||
|
||||
class AdminUserTestController < ActionController::Base
|
||||
protect_from_forgery
|
||||
|
||||
serialization_scope :current_admin
|
||||
before_filter { request.format = :json }
|
||||
|
||||
def current_admin
|
||||
TestUser.new('Bob', true)
|
||||
end
|
||||
|
||||
def render_new_user
|
||||
respond_with TestUser.new('pete', false), :serializer => AdminUserSerializer
|
||||
end
|
||||
end
|
||||
|
||||
tests AdminUserTestController
|
||||
|
||||
def test_override_scope_name_with_controller
|
||||
get :render_new_user
|
||||
assert_equal '{"admin_user":{"admin":true}}', @response.body
|
||||
end
|
||||
end
|
||||
@@ -1338,5 +1338,18 @@ class SerializerTest < ActiveModel::TestCase
|
||||
|
||||
end
|
||||
|
||||
def test_scope_name_method
|
||||
serializer = Class.new(ActiveModel::Serializer) do
|
||||
def has_permission?
|
||||
current_user.super_user?
|
||||
end
|
||||
end
|
||||
|
||||
user = User.new
|
||||
user.superuser = true
|
||||
post = Post.new(:title => 'Foo')
|
||||
|
||||
a_serializer = serializer.new(post, :scope => user, :scope_name => :current_user)
|
||||
assert a_serializer.has_permission?
|
||||
end
|
||||
end
|
||||
|
||||
Reference in New Issue
Block a user