Sha256: 4e2eb16e362cbd200035a5ab849c2c106a22c716b18083b18ca0a68dc9ff8c8e

Contents?: true

Size: 1.67 KB

Versions: 1

Compression:

Stored size: 1.67 KB

Contents

module Light
  module Decorator
    class Base
      # @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 - methods + Light::Decorator::FORCE_DELEGATE).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
            reflection = object.public_send(reflection_name)
            reflection.decorate(@options.reverse_merge(soft: true)) if reflection
          end
        end
      end
    end
  end
end

Version data entries

1 entries across 1 versions & 1 rubygems

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