From 173f21d942bea34e96e119ef9fe87a63660de6ae Mon Sep 17 00:00:00 2001 From: Terminator3 Date: Tue, 15 Sep 2015 15:55:35 -0500 Subject: [PATCH] outside controller use tutorial --- docs/README.md | 1 + docs/howto/outside_controller_use.md | 42 ++++++++++++++++++++++++++++ 2 files changed, 43 insertions(+) create mode 100644 docs/howto/outside_controller_use.md diff --git a/docs/README.md b/docs/README.md index 4f9172ab2..f0b4803f2 100644 --- a/docs/README.md +++ b/docs/README.md @@ -14,6 +14,7 @@ This is the documentation of AMS, it's focused on the **0.10.x version.** - [How to add root key](howto/add_root_key.md) - [How to add pagination links](howto/add_pagination_links.md) +- [Using AMS Outside Of Controllers](howto/outside_controller_use.md) ## Getting Help diff --git a/docs/howto/outside_controller_use.md b/docs/howto/outside_controller_use.md new file mode 100644 index 000000000..e74258c08 --- /dev/null +++ b/docs/howto/outside_controller_use.md @@ -0,0 +1,42 @@ +## Using AMS Outside Of A Controller + +### Serializing a resource + +In AMS versions 0.10 or later, serializing resources outside of the controller context is fairly simple: + +```ruby +# Create our resource +post = Post.create(title: "Sample post", body: "I love Active Model Serializers!") + +# Optional options parameters +options = {} + +# Create a serializable resource instance +serializable_resource = ActiveModel::SerializableResource.new(post, options) + +# Convert your resource into json +model_json = serializable_resource.as_json +``` + +### Retrieving a Resource's Active Model Serializer + +If you want to retrieve a serializer for a specific resource, you can do the following: + +```ruby +# Create our resource +post = Post.create(title: "Another Example", body: "So much fun.") + +# Optional options parameters +options = {} + +# Retrieve the default serializer for posts +serializer = ActiveModel::Serializer.serializer_for(post, options) +``` + +You could also retrieve the serializer via: + +```ruby +ActiveModel::SerializableResource.new(post, options).serializer +``` + +Both approaches will return an instance, if any, of the resource's serializer. \ No newline at end of file