Sha256: 078d000bd8d123b32a896980207c60a8f163f750ac9cfec89df9ba0947dbe748

Contents?: true

Size: 941 Bytes

Versions: 1

Compression:

Stored size: 941 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?(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

1 entries across 1 versions & 1 rubygems

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