Created
April 21, 2024 22:47
-
-
Save 0sc/b1bf4e61b41adcc7371abe97335c8fe8 to your computer and use it in GitHub Desktop.
Sample snippets for using jsonapi-rb with primitive types.
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
module IdGenerator | |
# some basic unique id generator | |
SEQ = (1..).to_enum | |
# id field is required by the JSONAPI spec and must be unique in an array | |
def self.included(klass) = klass.id { "_#{SEQ.next}" } | |
end | |
# --- | |
# serializers/string_serializer.rb | |
class StringSerializer < JSONAPI::Serializable::Resource | |
include IdGenerator | |
attribute(:permalink) { @object } | |
end | |
# --- | |
# serializers/hash_serializer.rb | |
class HashSerializer < JSONAPI::Serializable::Resource | |
include IdGenerator | |
attributes :foo, :baz # any hash key(s) | |
end | |
# --- | |
# controllers/foo_controller.rb | |
class FooController < ApplicationController | |
def strings | |
list = %w[foo bar baz quux fred] | |
render jsonapi: list, class: { String: StringSerializer } | |
end | |
def hash | |
list = { foo: :bar, baz: :quux} | |
render jsonapi: list, class: { Hash: HashSerializer } | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment