mirror of
https://github.com/ditkrg/active_model_serializers.git
synced 2026-01-22 22:06:50 +00:00
Add DSL for urls
This commit is contained in:
parent
98a3e5696e
commit
ad0859e262
@ -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
|
||||
|
||||
3
test/fixtures/poro.rb
vendored
3
test/fixtures/poro.rb
vendored
@ -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
|
||||
|
||||
26
test/serializers/urls_test.rb
Normal file
26
test/serializers/urls_test.rb
Normal 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
|
||||
Loading…
Reference in New Issue
Block a user