Sha256: 1a45b27a857abff0cc82a0a836dd3dfe2c7e181c5efc149781a563cf8fd2cf36

Contents?: true

Size: 923 Bytes

Versions: 1

Compression:

Stored size: 923 Bytes

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(object, params)
      return unless object

      value =
        if @block
          @block.arity.abs == 1 ? object.instance_eval(&@block) : object.instance_exec(object, params, &@block)
        elsif object.is_a?(Hash)
          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

1 entries across 1 versions & 1 rubygems

Version Path
bright_serializer-0.2.4 lib/bright_serializer/attribute.rb