Last active
October 12, 2015 01:00
-
-
Save NullVoxPopuli/99da5afdc970c8036150 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
require 'active_model' | |
require 'active_model_serializers' | |
class BaseModel | |
# provides self.model_name | |
include ActiveModel::Model | |
attr_accessor :id, :updated_at | |
def cache_key | |
"#{self.class.name.downcase}/#{self.id}-#{self.updated_at.strftime("%Y%m%d%H%M%S%9N")}" | |
end | |
def read_attribute_for_serialization(name) | |
send(name) | |
end | |
end | |
class Post < BaseModel | |
attr_accessor :name, :author_name | |
end | |
class PostSerializer < ActiveModel::Serializer | |
attributes :id, :name, :author | |
def author | |
object.author_name | |
end | |
end | |
post = Post.new | |
post.id = 1 | |
post.name = 'PORO AMS' | |
post.author_name = 'NVP' | |
resource = ActiveModel::SerializableResource.new(post, adapter: :json) | |
puts resource.serializable_hash # => {:post=>{:id=>1, :name=>"PORO AMS", :author=>"NVP"}} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment