From c3de52d7ed470433e9ecd44226518797c0a9f389 Mon Sep 17 00:00:00 2001 From: Jose and Yehuda Date: Mon, 26 Sep 2011 19:29:37 -0400 Subject: Initial implementation of ActiveModel::Serializer --- activemodel/lib/active_model.rb | 1 + activemodel/lib/active_model/serializer.rb | 46 ++++++++++++++++++++++++++++++ 2 files changed, 47 insertions(+) create mode 100644 activemodel/lib/active_model/serializer.rb (limited to 'activemodel/lib') 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 -- cgit v1.2.3