Provide Rails url_helpers via SerializationContext

This commit is contained in:
Ben Mills
2016-03-01 19:23:55 -07:00
parent 3ba5254a46
commit cc10928472
15 changed files with 177 additions and 52 deletions

View File

@@ -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

View File

@@ -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

View File

@@ -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).

View File

@@ -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