Commit e8d56d23 authored by Bob Van Landuyt's avatar Bob Van Landuyt 💬
Browse files

Allow reading a single method from the context

parent 811b7b5e
Loading
Loading
Loading
Loading
+11 −1
Original line number Diff line number Diff line
@@ -106,6 +106,12 @@ module Labkit
      end
    end

    def get_attribute(attribute)
      raw = call_or_value(data[log_key(attribute)])

      call_or_value(raw)
    end

    protected

    def assign_attributes(attributes)
@@ -130,9 +136,13 @@ module Labkit

    attr_reader :data

    def call_or_value(value)
      value.respond_to?(:call) ? value.call : value
    end

    def expand_data
      data.transform_values do |value|
        value = value.respond_to?(:call) ? value.call : value
        value = call_or_value(value)

        value.presence
      end.compact
+20 −0
Original line number Diff line number Diff line
@@ -279,6 +279,26 @@ describe Labkit::Context do
    end
  end

  describe "#get_attribute" do
    where(:set_context, :attribute, :expected_value) do
      [
        [{}, :caller_id, nil],
        [{ caller_id: "caller" }, :caller_id, "caller"],
        [{ caller_id: -> { "caller" } }, :caller_id, "caller"],
        [{ caller_id: -> { "caller" } }, "caller_id", "caller"],
        [{ caller_id: -> { "caller" } }, "meta.caller_id", "caller"],
      ]
    end

    with_them do
      it "returns the expected value for the attribute" do
        described_class.with_context(set_context) do |context|
          expect(context.get_attribute(attribute)).to eq(expected_value)
        end
      end
    end
  end

  def contexts
    described_class.__send__(:contexts)
  end