Skip to content

Instantly share code, notes, and snippets.

@0sc
Created April 21, 2024 22:47
Show Gist options
  • Save 0sc/b1bf4e61b41adcc7371abe97335c8fe8 to your computer and use it in GitHub Desktop.
Save 0sc/b1bf4e61b41adcc7371abe97335c8fe8 to your computer and use it in GitHub Desktop.
Sample snippets for using jsonapi-rb with primitive types.
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