Sha256: c79b540fa42116dd2699ce67009437f62731d23f721bec5c00e3ac63fac74b23

Contents?: true

Size: 1.62 KB

Versions: 1

Compression:

Stored size: 1.62 KB

Contents

module Light
  module Decorator
    class Decorate
      # @return original object
      attr_reader :object

      # Decorate the object
      #
      # @param [Object] object for decoration
      # @param [Hash] options
      #
      # @return [Object] decorated object
      def initialize(object, options = {})
        @object = object
        @options = options

        delegate_methods
        decorate_associations
      end

      # Check current ActiveRecord::Model is decorated or not
      #
      # @return [Bool]
      def decorated?
        true
      end

      # Current view scope
      #
      # @return [ActionView::Base]
      def helpers
        return @helpers if defined?(@helpers)
        @helpers = Light::Decorator::ViewContext.current
      end

      def ==(other)
        super || object == other
      end

      def eql?(other)
        super || object.eql?(other)
      end

      class << self
        alias decorate new
      end

      alias o object
      alias h helpers

      private

      def delegate_methods
        # It's more faster than using Forwardable
        (object.public_methods - Light::Decorator::NOT_DELEGATABLE_METHODS).each do |method|
          define_singleton_method method do |*args, &block|
            object.__send__(method, *args, &block)
          end
        end
      end

      def decorate_associations
        object.class.reflect_on_all_associations.map(&:name).each do |reflection_name|
          define_singleton_method reflection_name do
            object.public_send(reflection_name).decorate(@options.reverse_merge(soft: true))
          end
        end
      end
    end
  end
end

Version data entries

1 entries across 1 versions & 1 rubygems

Version Path
light-decorator-0.5.0 lib/light/decorator/decorate.rb