aboutsummaryrefslogtreecommitdiffstats
path: root/activemodel/lib
diff options
context:
space:
mode:
authorJose and Yehuda <wycats@gmail.com>2011-09-26 19:29:37 -0400
committerJose and Yehuda <wycats@gmail.com>2011-10-15 18:40:37 +0200
commitc3de52d7ed470433e9ecd44226518797c0a9f389 (patch)
tree42b91a52345f39ba2d824836fc4f1b5288cc90aa /activemodel/lib
parenta4c04a43cc96d9c94b7a5ecd5c7458fdc2f8617f (diff)
downloadrails-c3de52d7ed470433e9ecd44226518797c0a9f389.tar.gz
rails-c3de52d7ed470433e9ecd44226518797c0a9f389.tar.bz2
rails-c3de52d7ed470433e9ecd44226518797c0a9f389.zip
Initial implementation of ActiveModel::Serializer
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