From 3c30f0657b97cc1f61f542265efe16066be8503c Mon Sep 17 00:00:00 2001 From: Laura Steadman Date: Thu, 29 Jan 2015 17:10:09 -0700 Subject: [PATCH] Add support for Rails autoloading. --- README.md | 4 +++- lib/restpack_serializer/factory.rb | 2 +- lib/restpack_serializer/serializable.rb | 12 +++++++++++- 3 files changed, 15 insertions(+), 3 deletions(-) diff --git a/README.md b/README.md index d08ea1d..d69bdea 100644 --- a/README.md +++ b/README.md @@ -15,7 +15,9 @@ restpack_serializer allows you to quickly provide a set of RESTful endpoints for ## Getting Started ### For rails projects: -After adding the gem `restpack_serializer` to your Gemfile, add this code to `config/initializers/restpack_serializer.rb`: +Rails autoloading will automatically pull in top-level serializers. This means you no longer need to restart your server when changing serializers in development. If you previously had a restpack serializer initializer script, please remove it, as the two are not compatible. + +If your serializers or your model classes are nested in a module, you'll need to make sure you add this to your project in `config/initializers/restpack_serializer.rb`: ```ruby Dir[Rails.root.join('app/serializers/**/*.rb')].each do |path| diff --git a/lib/restpack_serializer/factory.rb b/lib/restpack_serializer/factory.rb index dd8d0cf..19d11c2 100644 --- a/lib/restpack_serializer/factory.rb +++ b/lib/restpack_serializer/factory.rb @@ -9,7 +9,7 @@ def self.create(*identifiers) def self.classify(identifier) normalised_identifier = identifier.to_s.underscore [normalised_identifier, normalised_identifier.singularize].each do |format| - klass = RestPack::Serializer.class_map[format] + klass = RestPack::Serializer.class_for_identifier(format) return klass.new if klass end diff --git a/lib/restpack_serializer/serializable.rb b/lib/restpack_serializer/serializable.rb index 770b66b..5405fec 100644 --- a/lib/restpack_serializer/serializable.rb +++ b/lib/restpack_serializer/serializable.rb @@ -13,7 +13,7 @@ module RestPack module Serializer extend ActiveSupport::Concern - mattr_accessor :class_map + @@class_map ||= {} included do @@ -22,6 +22,16 @@ module Serializer @@class_map[identifier.split('/').last] = self end + def self.class_for_identifier(identifier) + klass = begin + "#{identifier}_serializer".camelize.constantize + rescue NameError => e + nil + end + + klass ||= @@class_map[identifier] + end + include RestPack::Serializer::Paging include RestPack::Serializer::Resource include RestPack::Serializer::Single