diff options
author | Jose and Yehuda <wycats@gmail.com> | 2011-09-26 19:29:37 -0400 |
---|---|---|
committer | Jose and Yehuda <wycats@gmail.com> | 2011-10-15 18:40:37 +0200 |
commit | c3de52d7ed470433e9ecd44226518797c0a9f389 (patch) | |
tree | 42b91a52345f39ba2d824836fc4f1b5288cc90aa /activemodel/lib/active_model | |
parent | a4c04a43cc96d9c94b7a5ecd5c7458fdc2f8617f (diff) | |
download | rails-c3de52d7ed470433e9ecd44226518797c0a9f389.tar.gz rails-c3de52d7ed470433e9ecd44226518797c0a9f389.tar.bz2 rails-c3de52d7ed470433e9ecd44226518797c0a9f389.zip |
Initial implementation of ActiveModel::Serializer
Diffstat (limited to 'activemodel/lib/active_model')
-rw-r--r-- | activemodel/lib/active_model/serializer.rb | 46 |
1 files changed, 46 insertions, 0 deletions
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 |