Module: JSONAPI::Serializable::Resource::Relationships::DSL

Defined in:
lib/jsonapi/serializable/resource/relationships.rb

Overview

DSL methods for declaring relationships.

Instance Method Summary collapse

Instance Method Details

#inherited(klass) ⇒ Object



46
47
48
49
# File 'lib/jsonapi/serializable/resource/relationships.rb', line 46

def inherited(klass)
  super
  klass.relationship_blocks = relationship_blocks.dup
end

#relationship(name, options = {}, &block) ⇒ Object Also known as: has_many, has_one, belongs_to

Declare a relationship for this resource. The properties of the

relationship are set by providing a block in which the DSL methods
of +JSONAPI::Serializable::Relationship+ are called.

Examples:

relationship :posts do
  resources { @user.posts.map { |p| PostResource.new(post: p) } }
end
relationship :author do
  resources do
    @post.author && UserResource.new(user: @post.author)
  end
  data do
    { type: 'users', id: @post.author_id }
  end
  link(:self) do
    "http://api.example.com/posts/#{@post.id}/relationships/author"
  end
  link(:related) do
    "http://api.example.com/posts/#{@post.id}/author"
  end
  meta do
    { author_online: @post.author.online? }
  end
end

Parameters:

  • name (Symbol)

    The key of the relationship.

See Also:



81
82
83
84
85
86
87
# File 'lib/jsonapi/serializable/resource/relationships.rb', line 81

def relationship(name, options = {}, &block)
  rel_block = proc do
    data(options[:class]) { @object.public_send(name) }
    instance_eval(&block) unless block.nil?
  end
  relationship_blocks[name.to_sym] = rel_block
end