Sha256: 1c65d1344c4e2b31867dffbc0815c8b2bbc1e621cbff1894dad5956fdb9e6864

Contents?: true

Size: 1.26 KB

Versions: 2

Compression:

Stored size: 1.26 KB

Contents

require 'bundler/setup'
Bundler.require(:default)
# require 'active_support/core_ext/string'

module MongoMapper
  module Plugins
    module ToViewModel
      extend ActiveSupport::Concern
      
      module ClassMethods
        def to_view_model
          fields = keys.inject({}) do |memo, (k, v)|
            memo[k.to_s] = if v.type == ObjectId
              nil
            else
              v.type.new rescue nil
            end
            memo
          end
          
          relations = associations.inject({}) do |memo, (k, v)|
            memo[k.to_s] = [v.klass.to_view_model] if ['OneAssociation', 'ManyAssociation'].include?(v.class.to_s.split(/::/).last)
            memo
          end
          
          fields.merge(relations)
        end
      end
      
      module InstanceMethods
        def to_view_model
          fields = keys.inject({}) do |memo, (k, v)|
            memo[k.to_s] = send(k)
            memo
          end
          
          relations = associations.inject({}) do |memo, (k, v)|
            begin
              memo[k.to_s] = send(k).collect(&:to_view_model)
            rescue
              # Don't add to hash
            end
            memo
          end
          
          fields.merge(relations)
        end
      end
    end
  end
end

Version data entries

2 entries across 2 versions & 1 rubygems

Version Path
mm_to_view_model-0.1.1 lib/mm_to_view_model.rb
mm_to_view_model-0.1.0 lib/mm_to_view_model.rb