Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add basic support for 'current_user' #12

Merged
merged 2 commits into from Dec 12, 2013
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Binary file removed .DS_Store
Binary file not shown.
31 changes: 31 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -99,6 +99,37 @@ namespace 'foo', :serializer => :bar do
end
```

### current_user

One of the nice features of ActiveModel::Serializers is that it
provides access to the authorization context via the `current_user`.

In Grape, you can get the same behavior by defining a `current_user`
helper method:

```ruby
helpers do
def current_user
@current_user ||= User.where( :access_token => params[:token]).first
end

def authenticate!
error!('401 Unauthenticated', 401) unless current_user
end
end
```

Then, in your serializer, you could show or hide some elements
based on the current user's permissions:

```ruby
class PostSerializer < ActiveModel::Serializer
...
def include_admin_comments?
current_user.roles.member? :admin
end
end
```

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I'd love to see an example for an endpoint, how the code would look like.


### Full Example

Expand Down
13 changes: 11 additions & 2 deletions lib/grape-active_model_serializers/endpoint_extension.rb
Original file line number Diff line number Diff line change
Expand Up @@ -16,9 +16,18 @@ def route_options
options[:route_options]
end

def self.included(base)
mattr_accessor :_serialization_scope
self._serialization_scope = :current_user

base.class_eval do
def serialization_scope
send(_serialization_scope) if _serialization_scope && respond_to?(_serialization_scope, true)
end
end
end

def default_serializer_options; end
def serialization_scope; end
def _serialization_scope; end
def url_options; end
end

Expand Down
Binary file removed spec/.DS_Store
Binary file not shown.