Skip to content

Commit

Permalink
Move reusable code to a module
Browse files Browse the repository at this point in the history
  • Loading branch information
spastorino committed May 13, 2013
1 parent 0f96efa commit 6c6bc88
Show file tree
Hide file tree
Showing 2 changed files with 39 additions and 29 deletions.
34 changes: 5 additions & 29 deletions lib/active_model/array_serializer.rb
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
require 'active_model/serializable'
require "active_support/core_ext/class/attribute"
require 'active_support/dependencies'
require 'active_support/descendants_tracker'
Expand All @@ -15,6 +16,8 @@ module ActiveModel
class ArraySerializer
extend ActiveSupport::DescendantsTracker

include ActiveModel::Serializable

attr_reader :object, :options

class_attribute :root
Expand All @@ -33,35 +36,8 @@ def initialize(object, options={})
@object, @options = object, options
end

def meta_key
@options[:meta_key].try(:to_sym) || :meta
end

def include_meta(hash)
hash[meta_key] = @options[:meta] if @options.has_key?(:meta)
end

def as_json(*args)
@options[:hash] = hash = {}
@options[:unique_values] = {}

if root = @options[:root]
hash.merge!(root => serializable_array)
include_meta hash
hash
else
serializable_array
end
end

def to_json(*args)
if perform_caching?
cache.fetch expand_cache_key([self.class.to_s.underscore, cache_key, 'to-json']) do
super
end
else
super
end
def serialize
serializable_array
end

def serializable_array
Expand Down
34 changes: 34 additions & 0 deletions lib/active_model/serializable.rb
Original file line number Diff line number Diff line change
@@ -0,0 +1,34 @@
module ActiveModel
module Serializable
def meta_key
options[:meta_key].try(:to_sym) || :meta
end

def include_meta(hash)
hash[meta_key] = options[:meta] if options.has_key?(:meta)
end

def as_json(*args)
options[:hash] = hash = {}
options[:unique_values] = {}

if root = options[:root]
hash.merge!(root => serialize)
include_meta hash
hash
else
serialize
end
end

def to_json(*args)
if perform_caching?
cache.fetch expand_cache_key([self.class.to_s.underscore, cache_key, 'to-json']) do
super
end
else
super
end
end
end
end

0 comments on commit 6c6bc88

Please sign in to comment.