lib/yaks/mapper.rb in yaks-0.3.1 vs lib/yaks/mapper.rb in yaks-0.4.0.rc1

- old
+ new

@@ -1,63 +1,75 @@ # -*- coding: utf-8 -*- module Yaks class Mapper extend ClassMethods, Forwardable - include Util, MapLinks, SharedOptions + include Util, FP def_delegators 'self.class', :config def_delegators :config, :attributes, :links, :associations - attr_reader :subject, :options - private :subject, :options - alias object subject + attr_reader :object, :context - def initialize(subject, options = {}) - @subject = subject - @options = YAKS_DEFAULT_OPTIONS.merge(options) + def initialize(object, context) + @object = object + @context = context end - def to_resource - return NullResource.new if subject.nil? + def policy + context.fetch(:policy) + end + def env + context.fetch(:env) + end + + def call + return NullResource.new if object.nil? + Resource.new( - map_attributes, - map_links, - map_subresources + type: mapper_name, + attributes: map_attributes, + links: map_links, + subresources: map_subresources ) end + alias to_resource call - def profile_type - config.profile || policy.derive_profile_from_mapper(self) + def map_attributes + filter(attributes).each_with_object({}) do |attr, memo| + memo[attr] = load_attribute(attr) + end end - def map_attributes - filter(attributes).map &juxt(identity_function, method(:load_attribute)) + def map_links + links.map &send_with_args(:map_to_resource_link, self) end def map_subresources - attributes = filter(associations.map(&:name)) - associations.select{|assoc| attributes.include? assoc.name}.map do |association| - association.map_to_resource_pair( - profile_type, + attributes = filter(associations.map(&:name)) + associations = associations().select{|assoc| attributes.include? assoc.name } + associations.each_with_object({}) do |association, memo| + rel, subresource = association.create_subresource( + self, method(:load_association), - options.merge(parent: subject) + context ) + memo[rel] = subresource end end def load_attribute(name) - respond_to?(name) ? send(name) : subject.send(name) + respond_to?(name) ? public_send(name) : object.public_send(name) end alias load_association load_attribute - def profile - config.profile || policy.derive_missing_profile_from_mapper(self) - end - def filter(attrs) attrs + end + + def mapper_name + config.type || policy.derive_type_from_mapper_class(self.class) end end end