mirror of
https://github.com/ditkrg/active_model_serializers.git
synced 2026-01-25 15:23:06 +00:00
Provide Rails url_helpers via SerializationContext
This commit is contained in:
@@ -20,9 +20,11 @@ module ActiveModel
|
||||
|
||||
# Define a link on a serializer.
|
||||
# @example
|
||||
# link :self { "//example.com/posts/#{object.id}" }
|
||||
# link(:self) { resource_url(object) }
|
||||
# @example
|
||||
# link :self, "//example.com/user"
|
||||
# link(:self) { "http://example.com/resource/#{object.id}" }
|
||||
# @example
|
||||
# link :resource, "http://example.com/resource"
|
||||
#
|
||||
def link(name, value = nil, &block)
|
||||
_links[name] = block || value
|
||||
|
||||
@@ -1,7 +1,12 @@
|
||||
require 'active_support/core_ext/module/delegation'
|
||||
|
||||
module ActiveModelSerializers
|
||||
module Adapter
|
||||
class JsonApi
|
||||
class Link
|
||||
include SerializationContext.url_helpers
|
||||
delegate :default_url_options, to: SerializationContext
|
||||
|
||||
def initialize(serializer, value)
|
||||
@object = serializer.object
|
||||
@scope = serializer.scope
|
||||
|
||||
@@ -15,6 +15,11 @@ module ActiveModelSerializers
|
||||
end
|
||||
end
|
||||
|
||||
initializer 'active_model_serializers.prepare_serialization_context' do
|
||||
SerializationContext.url_helpers = Rails.application.routes.url_helpers
|
||||
SerializationContext.default_url_options = Rails.application.routes.default_url_options
|
||||
end
|
||||
|
||||
# This hook is run after the action_controller railtie has set the configuration
|
||||
# based on the *environment* configuration and before any config/initializers are run
|
||||
# and also before eager_loading (if enabled).
|
||||
|
||||
@@ -1,10 +1,24 @@
|
||||
module ActiveModelSerializers
|
||||
class SerializationContext
|
||||
class << self
|
||||
attr_writer :url_helpers, :default_url_options
|
||||
end
|
||||
|
||||
attr_reader :request_url, :query_parameters
|
||||
|
||||
def initialize(request)
|
||||
def initialize(request, options = {})
|
||||
@request_url = request.original_url[/\A[^?]+/]
|
||||
@query_parameters = request.query_parameters
|
||||
@url_helpers = options.delete(:url_helpers) || self.class.url_helpers
|
||||
@default_url_options = options.delete(:default_url_options) || self.class.default_url_options
|
||||
end
|
||||
|
||||
def self.url_helpers
|
||||
@url_helpers ||= Module.new
|
||||
end
|
||||
|
||||
def self.default_url_options
|
||||
@default_url_options ||= {}
|
||||
end
|
||||
end
|
||||
end
|
||||
|
||||
Reference in New Issue
Block a user