Skip to content

Instantly share code, notes, and snippets.

@fsubal
Last active June 23, 2024 14:29
Show Gist options
  • Save fsubal/5b817577607fce8f036cd6caa4fbd0e7 to your computer and use it in GitHub Desktop.
Save fsubal/5b817577607fce8f036cd6caa4fbd0e7 to your computer and use it in GitHub Desktop.
class JsonSerialize
include ActiveModel::Model
include ActiveModel::Attributes
include ActiveModel::Serializers::JSON
def initialize(attributes)
super()
attributes.each do |key, value|
self.public_send("#{key}=", value)
end
end
def self.from(**model)
new(model.attributes)
end
def self.from_many(*models)
Array.wrap(models).map { |model| from(model) }
end
end
class PaginationSerializer < JsonSerialize
attributes :total_count, :integer
attributes :total_pages, :integer
attributes :page, :integer
attributes :items, :integer
def self.from_pagination(models, item_class:)
new(
total_count: models.total_count,
total_pages: models.total_pages,
page: models.page,
items: item_class.from_many(models)
)
end
end
class ItemSerializer < JsonSerialize
attribute :name, :string
attribute :price, :integer
def is_public
published_at.present?
end
def attributes
super.merge(is_public:)
end
end
ItemSerializer.new(name: 'a', price: 1000)
ItemSerializer.new(name: 'a', price: '1000')
ItemSerializer.new(name: 'a', price: 'aaaa')
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment