Skip to content

Instantly share code, notes, and snippets.

@arubis
Created July 25, 2018 21:42
Show Gist options
  • Save arubis/e925282cc16e5de30cbaa2238161ffe2 to your computer and use it in GitHub Desktop.
Save arubis/e925282cc16e5de30cbaa2238161ffe2 to your computer and use it in GitHub Desktop.
# frozen_string_literal: true
# source: https://github.com/rails-api/active_model_serializers/blob/v0.10.6/docs/howto/upgrade_from_0_8_to_0_10.md#2-add-activemodelv08serializer
module ActiveModel::V08
class Serializer < ActiveModel::Serializer
include Rails.application.routes.url_helpers
# AMS 0.8 would delegate method calls from within the serializer to the
# object.
def method_missing(*args)
method = args.first
read_attribute_for_serialization(method)
end
alias_method :options, :instance_options
# Since attributes could be read from the `object` via `method_missing`,
# the `try` method did not behave as before. This patches `try` with the
# original implementation plus the addition of
# ` || object.respond_to?(a.first, true)` to check if the object responded to
# the given method.
def try(*a, &b)
if a.empty? || respond_to?(a.first, true) || object.respond_to?(a.first, true)
try!(*a, &b)
end
end
# AMS 0.8 would return nil if the serializer was initialized with a nil
# resource.
def serializable_hash(adapter_options = nil,
options = {},
adapter_instance =
self.class.serialization_adapter_instance)
object.nil? ? nil : super
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment