Sha256: 04a520f99509e478fc61b49090dbe153b19d6714873d3ed05c5db4b996dda3a9

Contents?: true

Size: 1.02 KB

Versions: 2

Compression:

Stored size: 1.02 KB

Contents

# frozen_string_literal: true

require_relative 'entity/base'

module BrightSerializer
  class Attribute
    attr_reader :key, :block, :condition, :entity
    attr_accessor :transformed_key

    def initialize(key, condition, entity, &block)
      @key = key
      @condition = condition
      @block = block
      @entity = entity ? Entity::Base.new(entity) : nil
    end

    def serialize(serializer_instance, object, params)
      return unless object

      value =
        if @block
          if @block.arity.abs == 1
            serializer_instance.instance_exec(object, &@block)
          else
            serializer_instance.instance_exec(object, params, &@block)
          end
        elsif object.is_a?(Hash)
          object.key?(key) ? object[key] : object[key.to_s]
        else
          object.send(key)
        end

      value.respond_to?(:serializable_hash) ? value.serializable_hash : value
    end

    def condition?(object, params)
      return true unless @condition

      @condition.call(object, params)
    end
  end
end

Version data entries

2 entries across 2 versions & 1 rubygems

Version Path
bright_serializer-0.3.1 lib/bright_serializer/attribute.rb
bright_serializer-0.3.0 lib/bright_serializer/attribute.rb