aboutsummaryrefslogtreecommitdiffstats
path: root/activemodel/lib
diff options
context:
space:
mode:
Diffstat (limited to 'activemodel/lib')
-rw-r--r--activemodel/lib/active_model.rb1
-rw-r--r--activemodel/lib/active_model/serializer.rb46
2 files changed, 47 insertions, 0 deletions
diff --git a/activemodel/lib/active_model.rb b/activemodel/lib/active_model.rb
index d0e2a6f39c..28765b00bb 100644
--- a/activemodel/lib/active_model.rb
+++ b/activemodel/lib/active_model.rb
@@ -43,6 +43,7 @@ module ActiveModel
autoload :Observer, 'active_model/observing'
autoload :Observing
autoload :SecurePassword
+ autoload :Serializer
autoload :Serialization
autoload :TestCase
autoload :Translation
diff --git a/activemodel/lib/active_model/serializer.rb b/activemodel/lib/active_model/serializer.rb
new file mode 100644
index 0000000000..2eca3ebc5e
--- /dev/null
+++ b/activemodel/lib/active_model/serializer.rb
@@ -0,0 +1,46 @@
+require "active_support/core_ext/class/attribute"
+require "active_support/core_ext/string/inflections"
+require "set"
+
+module ActiveModel
+ class Serializer
+ class_attribute :_attributes
+ self._attributes = Set.new
+
+ def self.attributes(*attrs)
+ self._attributes += attrs
+ end
+
+ attr_reader :object, :scope
+
+ def self.inherited(klass)
+ name = klass.name.demodulize.underscore.sub(/_serializer$/, '')
+
+ klass.class_eval do
+ alias_method name.to_sym, :object
+ end
+ end
+
+ def initialize(object, scope)
+ @object, @scope = object, scope
+ end
+
+ def as_json(*)
+ serializable_hash
+ end
+
+ def serializable_hash(*)
+ attributes
+ end
+
+ def attributes
+ hash = {}
+
+ _attributes.each do |name|
+ hash[name] = @object.read_attribute_for_serialization(name)
+ end
+
+ hash
+ end
+ end
+end