Skip to content

Commit

Permalink
Initialize Context from JSON-encoded ENV variables
Browse files Browse the repository at this point in the history
  • Loading branch information
Sija committed Feb 4, 2020
1 parent 33a2810 commit def51fa
Show file tree
Hide file tree
Showing 2 changed files with 59 additions and 2 deletions.
38 changes: 38 additions & 0 deletions spec/raven/context_spec.cr
Original file line number Diff line number Diff line change
@@ -0,0 +1,38 @@
require "../spec_helper"

describe Raven::Context do
{% for key in %i(user extra tags) %}
{% env_key = "SENTRY_CONTEXT_#{key.upcase.id}" %}

context %(with ENV["{{ env_key.id }}"]?) do
it "initializes from valid JSON-encoded string" do
with_clean_env do
ENV[{{ env_key }}] = {foo: :bar}.to_json

context = Raven::Context.new
context.{{ key.id }}.should eq({"foo" => "bar"})
end
end

it "raises when JSON-encoded string is not a Hash" do
with_clean_env do
ENV[{{ env_key }}] = (0..3).to_a.to_json

expect_raises(Raven::Error, {{ env_key }}) do
Raven::Context.new
end
end
end

it "raises on invalid JSON-encoded string" do
with_clean_env do
ENV[{{ env_key }}] = "foo"

expect_raises(Raven::Error, {{ env_key }}) do
Raven::Context.new
end
end
end
end
{% end %}
end
23 changes: 21 additions & 2 deletions src/raven/context.cr
Original file line number Diff line number Diff line change
Expand Up @@ -36,10 +36,29 @@ module Raven
any_json_property :contexts, :extra, :tags, :user

def initialize
@contexts = {
self.contexts = {
os: self.class.os_context,
runtime: self.class.runtime_context,
}.to_any_json
}
initialize_from_env
end

protected def initialize_from_env
{% for key in %i(user extra tags) %}
{% env_key = "SENTRY_CONTEXT_#{key.upcase.id}" %}

if %context = ENV[{{ env_key }}]?.presence
begin
if %json = JSON.parse(%context).as_h?
self.{{ key.id }}.merge!(%json)
else
raise Raven::Error.new("`{{ env_key.id }}` must contain a JSON-encoded hash")
end
rescue %e : JSON::ParseException
raise Raven::Error.new("Invalid JSON string in `{{ env_key.id }}`", cause: %e)
end
end
{% end %}
end
end
end

0 comments on commit def51fa

Please sign in to comment.