Add DSL for urls

This commit is contained in:
Jordan Faust 2014-09-01 13:44:22 -05:00
parent 98a3e5696e
commit ad0859e262
3 changed files with 39 additions and 0 deletions

View File

@ -9,11 +9,13 @@ module ActiveModel
class << self
attr_accessor :_attributes
attr_accessor :_associations
attr_accessor :_urls
end
def self.inherited(base)
base._attributes = []
base._associations = {}
base._urls = []
end
def self.attributes(*attrs)
@ -62,6 +64,14 @@ module ActiveModel
end
end
def self.url(attr)
@_urls.push attr
end
def self.urls(*attrs)
@_urls.concat attrs
end
def self.serializer_for(resource)
if resource.respond_to?(:to_ary)
config.array_serializer

View File

@ -31,6 +31,8 @@ end
class ProfileSerializer < ActiveModel::Serializer
attributes :name, :description
urls :posts, :comments
end
Post = Class.new(Model)
@ -40,6 +42,7 @@ PostSerializer = Class.new(ActiveModel::Serializer) do
attributes :title, :body, :id
has_many :comments
url :comments
end
CommentSerializer = Class.new(ActiveModel::Serializer) do

View File

@ -0,0 +1,26 @@
require 'test_helper'
module ActiveModel
class Serializer
class UrlsTest < Minitest::Test
def setup
@profile = Profile.new({ name: 'Name 1', description: 'Description 1', comments: 'Comments 1' })
@post = Post.new({ title: 'New Post', body: 'Body' })
@comment = Comment.new({ id: 1, body: 'ZOMG A COMMENT' })
@post.comments = [@comment]
@profile_serializer = ProfileSerializer.new(@profile)
@post_serializer = PostSerializer.new(@post)
end
def test_urls_definition
assert_equal([:posts, :comments], @profile_serializer.class._urls)
end
def test_url_definition
assert_equal([:comments], @post_serializer.class._urls)
end
end
end
end