Sha256: e605d4f1f80b34d5cb5e1dfd1cd04dc74257fda45d855dcc3bb8e57c67bfc6fc

Contents?: true

Size: 1.85 KB

Versions: 6

Compression:

Stored size: 1.85 KB

Contents

require 'active_support/concern'
require_relative "options"
require_relative "serializable/attributes"
require_relative "serializable/paging"
require_relative "serializable/resource"
require_relative "serializable/side_loading"

module RestPack
  module Serializer
    extend ActiveSupport::Concern

    include RestPack::Serializer::Paging
    include RestPack::Serializer::Resource
    include RestPack::Serializer::Attributes
    include RestPack::Serializer::SideLoading

    class InvalidInclude < Exception; end

    def as_json(model, context = {})
      @model, @context = model, context

      data = {}
      if self.class.serializable_attributes.present?
        self.class.serializable_attributes.each do |key, name|
          data[key] = self.send(name) if include_attribute?(name)
        end
      end

      add_custom_attributes(data)
      add_links(model, data)

      data
    end

    def custom_attributes
      {}
    end

    private

    def add_custom_attributes(data)
      custom = custom_attributes
      data.merge!(custom) if custom
    end

    def add_links(model, data)
      self.class.associations.each do |association|
        if association.macro == :belongs_to
          data[:links] ||= {}
          foreign_key_value = model.send(association.foreign_key)
          if foreign_key_value
            data[:links][association.name.to_sym] = foreign_key_value.to_s
          end
        end
      end
      data
    end

    def include_attribute?(name)
      self.send("include_#{name}?".to_sym)
    end

    module ClassMethods
      attr_accessor :model_class, :key
      def as_json(model, context = {})
        new.as_json(model, context)
      end

      def model_class
        @model_class || self.name.chomp('Serializer').constantize
      end

      def key
        (@key || self.model_class.send(:table_name)).to_sym
      end

    end
  end
end

Version data entries

6 entries across 6 versions & 1 rubygems

Version Path
restpack_serializer-0.4.2 lib/restpack_serializer/serializable.rb
restpack_serializer-0.4.1 lib/restpack_serializer/serializable.rb
restpack_serializer-0.2.16 lib/restpack_serializer/serializable.rb
restpack_serializer-0.2.15 lib/restpack_serializer/serializable.rb
restpack_serializer-0.2.14 lib/restpack_serializer/serializable.rb
restpack_serializer-0.2.13 lib/restpack_serializer/serializable.rb