<?xml version="1.0" encoding="UTF-8"?><rss version="2.0"
	xmlns:content="http://purl.org/rss/1.0/modules/content/"
	xmlns:wfw="http://wellformedweb.org/CommentAPI/"
	xmlns:dc="http://purl.org/dc/elements/1.1/"
	xmlns:atom="http://www.w3.org/2005/Atom"
	xmlns:sy="http://purl.org/rss/1.0/modules/syndication/"
	xmlns:slash="http://purl.org/rss/1.0/modules/slash/"
	>

<channel>
	<title>Rails &#8211; Other Things</title>
	<atom:link href="https://blog.adamzolo.com/category/rails/feed/" rel="self" type="application/rss+xml" />
	<link>https://blog.adamzolo.com</link>
	<description>Blog about Things by Adam Zolotarev</description>
	<lastBuildDate>Sat, 09 May 2026 14:00:17 +0000</lastBuildDate>
	<language>en-US</language>
	<sy:updatePeriod>
	hourly	</sy:updatePeriod>
	<sy:updateFrequency>
	1	</sy:updateFrequency>
	<generator>https://wordpress.org/?v=6.9.4</generator>
	<item>
		<title>Using tools for LLM&#8217;s instead of asking</title>
		<link>https://blog.adamzolo.com/claude-api-tool-use-vs-prompting/</link>
					<comments>https://blog.adamzolo.com/claude-api-tool-use-vs-prompting/#respond</comments>
		
		<dc:creator><![CDATA[Adam Zolo]]></dc:creator>
		<pubDate>Tue, 17 Feb 2026 03:26:32 +0000</pubDate>
				<category><![CDATA[AI]]></category>
		<category><![CDATA[Rails]]></category>
		<category><![CDATA[Ruby]]></category>
		<guid isPermaLink="false">https://blog.adamzolo.com/?p=1106</guid>

					<description><![CDATA[I have a Rails app that sends user-provided text to Claude for analysis and displays structured results in the UI. The response needs to be JSON so I can render it. However longer inputs sometimes would generate errors. Longer inputs meant longer system prompts and longer responses. The logs showed: Analysis failed: expected ',' or&#8230;<p><a class="more-link" href="https://blog.adamzolo.com/claude-api-tool-use-vs-prompting/" title="Continue reading &#8216;Using tools for LLM&#8217;s instead of asking&#8217;">Continue reading <span class="meta-nav">&#8594;</span></a></p>]]></description>
										<content:encoded><![CDATA[<p>I have a Rails app that sends user-provided text to Claude for analysis and displays structured results in the UI. The response needs to be JSON so I can render it.</p>
<p>However longer inputs sometimes would generate errors. Longer inputs meant longer system prompts and longer responses.</p>
<p>The logs showed:</p>
<pre><code>Analysis failed: expected ',' or '}' after object value</code></pre>
<p>Claude was generating valid-looking JSON that wasn&#8217;t actually valid. A dropped comma deep in a large response object. The longer the response, the more likely this happened.</p>
<h2>The Old Approach: Prompt Engineering + Defensive Parsing</h2>
<p>My system prompt included a 28-line block demanding JSON output:</p>
<pre><code class="language-ruby">SYSTEM_PROMPT = &lt;&lt;~PROMPT
  ...
  CRITICAL INSTRUCTIONS:
  - You MUST ALWAYS respond with valid JSON. No exceptions. No explanations outside JSON.
  - NEVER respond with plain text - always use the JSON format.

  You MUST ALWAYS respond in JSON format with the following structure (no exceptions):
  {
    "score": 0-100,
    "level": "low|medium|high",
    "summary": "Brief overall assessment",
    "items": [
      {
        "title": "Issue name",
        "description": "What's wrong",
        "severity": "low|medium|high"
      }
    ],
    "recommendations": [
      "Specific actionable suggestion 1",
      "Specific actionable suggestion 2"
    ]
  }
PROMPT</code></pre>
<p>Despite all the shouting in the prompt, Claude would sometimes:</p>
<ul>
<li>Wrap the JSON in markdown code fences (<code>```json ... ```</code>)</li>
<li>Add explanatory text after the closing brace</li>
<li>Drop commas in deeply nested objects on long responses</li>
<li>Return plain text when it decided the input wasn&#8217;t suitable for analysis</li>
</ul>
<p>So I built a pipeline of defensive code to handle all of this.</p>
<p><strong>Step 1: Extract JSON from whatever Claude returned.</strong> A brace-matching parser that stripped markdown fences, found the first <code>{</code>, tracked nesting depth while respecting string escaping, and separated trailing notes:</p>
<pre><code class="language-ruby">def extract_json_and_note(text)
  text = text.strip
  if text.start_with?("```")
    text = text.sub(/A```(?:json|JSON)?s*/, "").sub(/s*```z/, "").strip
  end

  start_idx = text.index("{")
  return [text, nil, false] if start_idx.nil?

  brace_count = 0
  in_string = false
  escape_next = false

  text[start_idx..].each_char.with_index do |char, idx|
    if escape_next
      escape_next = false
      next
    end
    case char
    when "\" then escape_next = true if in_string
    when '"'  then in_string = !in_string unless escape_next
    when "{"  then brace_count += 1 unless in_string
    when "}"
      brace_count -= 1 unless in_string
      if brace_count == 0
        end_idx = start_idx + idx
        json_text = text[start_idx..end_idx]
        note = text[(end_idx + 1)..].strip.presence
        return [json_text, note, true]
      end
    end
  end

  [text, nil, false]
end</code></pre>
<p><strong>Step 2: Normalize missing fields</strong> because Claude might omit arrays for edge cases:</p>
<pre><code class="language-ruby">def normalize_response!(result)
  result["score"] ||= 0
  result["level"] ||= "unknown"
  result["summary"] ||= "Analysis complete"
  result["items"] ||= []
  result["recommendations"] ||= []
  result["score"] = result["score"].to_i if result["score"].is_a?(String)
end</code></pre>
<p><strong>Step 3: Validate the structure</strong> because even after parsing, I couldn&#8217;t trust it:</p>
<pre><code class="language-ruby">def validate_response_structure!(result)
  required_keys = %w[score level summary items recommendations]
  missing_keys = required_keys - result.keys
  raise "Invalid response structure: missing keys #{missing_keys.join(', ')}" if missing_keys.any?

  score = result["score"]
  unless score.is_a?(Integer) &amp;&amp; score &gt;= 0 &amp;&amp; score &lt;= 100
    raise "Invalid score: must be integer 0-100, got #{score.inspect}"
  end

  %w[items recommendations].each do |key|
    unless result[key].is_a?(Array)
      raise "Invalid #{key}: expected array, got #{result[key].class}"
    end
  end
end</code></pre>
<p>All of this existed because I was asking an LLM to format its own output as JSON via natural language instructions. I was writing a fragile parser for a format the model was never <em>constrained</em> to produce.</p>
<h2>The Fix: Tool Use</h2>
<p>Anthropic&#8217;s tool use API (also called function calling) lets you define a JSON schema that Claude <em>must</em> conform to. Instead of asking Claude to output JSON, you tell the API: &#8220;call this function with these typed parameters.&#8221; Claude&#8217;s response is guaranteed to match the schema.</p>
<p>Here&#8217;s the schema definition:</p>
<pre><code class="language-ruby">ANALYSIS_TOOL = {
  name: "analyze",
  description: "Return the structured analysis results",
  input_schema: {
    type: "object",
    required: ["score", "level", "summary", "items", "recommendations"],
    properties: {
      score: { type: "integer", description: "Overall score from 0 (safe) to 100 (dangerous)" },
      level: { type: "string", enum: ["low", "medium", "high"] },
      summary: { type: "string", description: "Brief overall assessment" },
      items: {
        type: "array",
        items: {
          type: "object",
          required: ["title", "description", "severity"],
          properties: {
            title:       { type: "string" },
            description: { type: "string" },
            severity:    { type: "string", enum: ["low", "medium", "high"] }
          }
        }
      },
      recommendations: { type: "array", items: { type: "string" } }
    }
  }
}.freeze</code></pre>
<p>The API call adds two parameters:</p>
<pre><code class="language-ruby">response = client.messages.create(
  model: model,
  max_tokens: max_tokens,
  system: [{ type: "text", text: system_prompt }],
  messages: [{ role: "user", content: user_message }],
  tools: [ANALYSIS_TOOL],
  tool_choice: { type: "tool", name: "analyze" }
)</code></pre>
<p><code>tools:</code> defines the schema. <code>tool_choice:</code> with <code>type: "tool"</code> forces Claude to use it — no chance of returning prose instead.</p>
<p>Response extraction is three lines:</p>
<pre><code class="language-ruby">tool_block = response.content.find { |b| b.type.to_s == "tool_use" }
raise "No tool_use block in response" unless tool_block
result = tool_block.input.transform_keys(&amp;:to_s)</code></pre>
<p>That&#8217;s it. <code>tool_block.input</code> is already a parsed hash. No <code>JSON.parse</code>, no brace matching, no markdown stripping, no comma repair.</p>
<h2>The Result</h2>
<p><strong>Deleted:</strong> ~160 lines from the service, ~250 lines from tests..</p>
<p><strong>Added:</strong> ~30 lines for the schema definition, 2 parameters on the API call, 3 lines of response extraction.</p>
<p>The system prompt shrank too. The 28 lines of &#8220;YOU MUST RESPOND IN JSON&#8221; instructions disappeared entirely. The prompt now focuses on <em>what</em> to analyze, not <em>how</em> to format the output.</p>
<p>The user message went from <code>"Analyze this and respond with JSON only:"</code> to just <code>"Analyze this:"</code>.</p>
<h2>When Should You Use This?</h2>
<p>Any time you want structured output from an LLM. If you&#8217;re writing regex to fix JSON commas, building brace-matching parsers, or adding &#8220;RESPOND IN JSON ONLY&#8221; to your prompts: switch to tool use. The schema is self-documenting, the output is guaranteed valid, and you delete code instead of writing it.</p>
<p>The one caveat: tool use constrains the <em>structure</em> but not the <em>content</em>. Claude can still put whatever it wants in a string field. You still need to validate that a score is in a sensible range or that enum values match your expectations. But &#8220;validate the values&#8221; is a much smaller problem than &#8220;parse arbitrary text that might be JSON.&#8221;</p>
]]></content:encoded>
					
					<wfw:commentRss>https://blog.adamzolo.com/claude-api-tool-use-vs-prompting/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
		<item>
		<title>Idempotent Stripe Webhooks</title>
		<link>https://blog.adamzolo.com/idempotent-stripe-webhooks/</link>
					<comments>https://blog.adamzolo.com/idempotent-stripe-webhooks/#respond</comments>
		
		<dc:creator><![CDATA[Adam Zolo]]></dc:creator>
		<pubDate>Thu, 12 Feb 2026 11:37:48 +0000</pubDate>
				<category><![CDATA[Rails]]></category>
		<category><![CDATA[Stripe]]></category>
		<guid isPermaLink="false">https://blog.adamzolo.com/?p=1097</guid>

					<description><![CDATA[How to Implement Idempotent Stripe Webhooks in Rails Stripe can send the same webhook event more than once. Network timeouts, retries, and infrastructure hiccups all mean your endpoint might process the same event twice, charging a customer double, creating duplicate subscriptions, or corrupting your data. The fix is idempotency: making your webhook handler safe to&#8230;<p><a class="more-link" href="https://blog.adamzolo.com/idempotent-stripe-webhooks/" title="Continue reading &#8216;Idempotent Stripe Webhooks&#8217;">Continue reading <span class="meta-nav">&#8594;</span></a></p>]]></description>
										<content:encoded><![CDATA[
<h1 class="wp-block-heading">How to Implement Idempotent Stripe Webhooks in Rails</h1>



<p>Stripe can send the same webhook event more than once. Network timeouts, retries, and infrastructure hiccups all mean your endpoint might process the same event twice, charging a customer double, creating duplicate subscriptions, or corrupting your data.</p>



<p>The fix is idempotency: making your webhook handler safe to call multiple times with the same event.</p>



<h2 class="wp-block-heading">The Problem</h2>



<p>Every Stripe event has a unique ID like <code>evt_1abc123</code>. Stripe guarantees this ID is unique, but your endpoint has no such guarantee about delivery. From the <a href="https://docs.stripe.com/webhooks#handle-duplicate-events">Stripe docs</a>:</p>



<blockquote class="wp-block-quote is-layout-flow wp-block-quote-is-layout-flow">
<p>Webhook endpoints might occasionally receive the same event more than once. You can guard against duplicated event receipt by making your event processing idempotent.</p>
</blockquote>



<p>Without protection, a retried <code>invoice.paid</code> event could credit a user&#8217;s account twice or trigger duplicate emails.</p>



<h2 class="wp-block-heading">The Solution</h2>



<p>Track every processed event ID in your database. Before handling an event, check if you&#8217;ve already seen it. If yes, skip it.</p>



<h3 class="wp-block-heading">Step 1: Create the Table</h3>


<div class="wp-block-syntaxhighlighter-code "><pre class="brush: ruby; title: ; notranslate">
# db/migrate/xxx_create_stripe_webhook_events.rb
class CreateStripeWebhookEvents &lt; ActiveRecord::Migration&#x5B;8.1]
  def change
    create_table :stripe_webhook_events do |t|
      t.string :stripe_event_id, null: false
      t.string :event_type
      t.datetime :processed_at
      t.timestamps
    end

    add_index :stripe_webhook_events, :stripe_event_id, unique: true
  end
end
</pre></div>


<p>The unique index on <code>stripe_event_id</code> is the key. Even if two requests arrive simultaneously, the database constraint guarantees only one INSERT succeeds.</p>



<h3 class="wp-block-heading">Step 2: Create the Model</h3>


<div class="wp-block-syntaxhighlighter-code "><pre class="brush: ruby; title: ; notranslate">
# app/models/stripe_webhook_event.rb
class StripeWebhookEvent &lt; ApplicationRecord
  validates :stripe_event_id, presence: true, uniqueness: true

  def self.process(stripe_event_id, event_type:)
    create!(
      stripe_event_id: stripe_event_id,
      event_type: event_type,
      processed_at: Time.current
    )
    true
  rescue ActiveRecord::RecordNotUnique, ActiveRecord::RecordInvalid
    false
  end
end
</pre></div>


<p><code>process</code> returns <code>true</code> if this is a new event, <code>false</code> if it&#8217;s a duplicate. We rescue both exceptions because:</p>



<ul class="wp-block-list">
<li><code>RecordNotUnique</code> — the DB unique constraint catches concurrent duplicate inserts</li>



<li><code>RecordInvalid</code> — the model-level uniqueness validation catches sequential duplicates</li>
</ul>



<h3 class="wp-block-heading">Step 3: Use It in Your Webhook Handler</h3>


<div class="wp-block-syntaxhighlighter-code "><pre class="brush: plain; title: ; notranslate">
# app/services/stripe_webhook_handler.rb
def process!
  event = verify_signature!

  unless StripeWebhookEvent.process(event.id, event_type: event.type)
    Rails.logger.info(&quot;Skipping duplicate webhook: #{event.id}&quot;)
    return { status: &quot;success&quot;, duplicate: true }
  end

  handle_event(event)
end
</pre></div>


<p>The check goes right after signature verification and before any business logic. If it&#8217;s a duplicate, we return a success response (so Stripe doesn&#8217;t keep retrying) and skip processing.</p>



<h3 class="wp-block-heading">Step 4: Return 200 for Duplicates</h3>



<p>This is important — always return a 2xx status for duplicates:</p>


<div class="wp-block-syntaxhighlighter-code "><pre class="brush: ruby; title: ; notranslate">
# app/controllers/webhooks_controller.rb
def stripe
  handler = StripeWebhookHandler.new(
    payload: request.body.read,
    signature: request.env&#x5B;&quot;HTTP_STRIPE_SIGNATURE&quot;]
  )

  result = handler.process!
  render json: result, status: :ok
rescue StripeWebhookHandler::WebhookError =&gt; e
  render json: { error: e.message }, status: :bad_request
end
</pre></div>


<p>If you return an error for a duplicate, Stripe will keep retrying — which is the opposite of what you want.</p>



<h2 class="wp-block-heading">Cleanup</h2>



<p>Over time, the <code>stripe_webhook_events</code> table will grow. Add a periodic cleanup job to prune old records:</p>


<div class="wp-block-syntaxhighlighter-code "><pre class="brush: plain; title: ; notranslate">
# Keep 90 days of webhook history
StripeWebhookEvent.where(&quot;created_at &amp;lt; ?&quot;, 90.days.ago).delete_all
</pre></div>


<p>Stripe retries happen within hours, not months, so 90 days is more than enough.</p>



<h2 class="wp-block-heading">Summary</h2>



<ol class="wp-block-list">
<li>Create a table with a unique index on <code>stripe_event_id</code></li>



<li>Attempt an INSERT before processing — if it fails, it&#8217;s a duplicate</li>



<li>Always return 200 for duplicates so Stripe stops retrying</li>



<li>The database constraint handles race conditions that application-level checks can&#8217;t</li>
</ol>



<p></p>
]]></content:encoded>
					
					<wfw:commentRss>https://blog.adamzolo.com/idempotent-stripe-webhooks/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
		<item>
		<title>Building Clausy: A Contract Analysis Tool with Rails 8 and Claude AI</title>
		<link>https://blog.adamzolo.com/building-clausy-a-contract-analysis-tool-with-rails-8-and-claude-ai/</link>
					<comments>https://blog.adamzolo.com/building-clausy-a-contract-analysis-tool-with-rails-8-and-claude-ai/#respond</comments>
		
		<dc:creator><![CDATA[Adam Zolo]]></dc:creator>
		<pubDate>Sun, 08 Feb 2026 21:07:19 +0000</pubDate>
				<category><![CDATA[AI]]></category>
		<category><![CDATA[Rails]]></category>
		<category><![CDATA[Ruby]]></category>
		<category><![CDATA[Web]]></category>
		<guid isPermaLink="false">https://blog.adamzolo.com/?p=1090</guid>

					<description><![CDATA[I just launched https://clausyapp.com, a web app that uses AI to analyze contracts and highlight potential issues. You upload a PDF/images or paste text, and Claude AI reads through it to find things like unlimited liability clauses, auto-renewal terms, or aggressive IP assignment language. Why I Built This I&#8217;ve signed a enough contracts over the&#8230;<p><a class="more-link" href="https://blog.adamzolo.com/building-clausy-a-contract-analysis-tool-with-rails-8-and-claude-ai/" title="Continue reading &#8216;Building Clausy: A Contract Analysis Tool with Rails 8 and Claude AI&#8217;">Continue reading <span class="meta-nav">&#8594;</span></a></p>]]></description>
										<content:encoded><![CDATA[
<p>I just launched https://clausyapp.com, a web app that uses AI to analyze contracts and highlight potential issues. You upload a PDF/images or paste text, and Claude AI reads through it to find things like unlimited liability clauses, auto-renewal terms, or aggressive IP assignment language.</p>



<h2 class="wp-block-heading">Why I Built This</h2>



<p>I&#8217;ve signed a enough contracts over the years, and I was never quite sure if I was missing something important buried in the legal language. I&#8217;d skim through them, but let&#8217;s be honest – I didn&#8217;t understand half of it. Getting a lawyer to review every contract is also just not something I&#8217;m going to do, unless it&#8217;s something really big.</p>



<p>I figured: AI is pretty good at reading and understanding text now. And based on how many of these AI contract analysis tools are out there, it&#8217;s the new TODO app in the age of AI.</p>



<h2 class="wp-block-heading">The Stack</h2>



<p>I went with a Rails 8 monolith because I wanted something I could ship quickly and maintain solo:</p>



<ul class="wp-block-list">
<li>Rails 8 with Hotwire (Turbo + Stimulus)</li>



<li>Anthropic&#8217;s Claude API</li>



<li>Solid Queue for background jobs with priority queues (paid users get faster processing)</li>



<li>Solid Cache for caching and rate limits</li>



<li>Stripe for subscriptions and billing</li>



<li>Tesseract OCR for extracting text from scanned images (JPG, PNG, WebP, HEIC)</li>



<li>Kamal for deployment</li>
</ul>



<p>Everything runs in Docker containers. No separate frontend framework, no microservices. Just a straightforward Rails app that does one thing well.</p>



<h2 class="wp-block-heading">Technical Security Challenges</h2>



<ol class="wp-block-list">
<li><strong>File Processing Security</strong>
<ul class="wp-block-list">
<li>Magic byte validation – Don&#8217;t trust file extensions. I check the actual file signature to verify it&#8217;s really a PDF or DOCX.</li>



<li>Size limits – DOCX files are zip archives, so I enforce size limits before decompression to prevent zip bombs.</li>



<li>Immediate deletion – Original files are deleted right after text extraction. No long-term storage of sensitive documents.</li>



<li>Command injection prevention – Only use safe extraction tools, never shell out with user-provided filenames.</li>
</ul>
</li>



<li><strong>Server Access</strong>
<ul class="wp-block-list">
<li>Firewall at the provider level </li>



<li>Firewall at the node level (ufw)</li>



<li>ssh through certs only, limit access to specific IP&#8217;s</li>



<li>Cloudflare</li>
</ul>
</li>



<li><strong>Application </strong>Security
<ul class="wp-block-list">
<li>Devise authentication &#8211; Industry-standard auth framework</li>



<li>CSRF protection &#8211; Rails CSRF tokens on all POST/PUT/PATCH/DELETE requests</li>



<li>UUID-based URLs &#8211; Guest contracts use UUIDs (prevents enumeration attacks)</li>



<li>Rate Limits (Rack::Attack)</li>



<li>CSP Policy
<ul class="wp-block-list">
<li>No unsafe-eval &#8211; Prevents eval() attacks</li>



<li>Whitelisted script sources &#8211; Only self, HTTPS, Stripe, Cloudflare allowed</li>



<li>No object embeds &#8211; object_src :none blocks Flash/plugin attacks</li>



<li>Nonce-based scripts &#8211; Importmap scripts use session-based nonces</li>



<li>HTTPS enforced &#8211; All resources loaded over HTTPS</li>
</ul>
</li>



<li>Input Validation</li>
</ul>
</li>



<li>Fraud Prevention
<ul class="wp-block-list">
<li>Email history tracking &#8211; SHA256 email hashing &#8211; Email hashes stored, not plain emails</li>
</ul>
</li>



<li>Payment Security
<ul class="wp-block-list">
<li>Stripe webhook verification &#8211; Signature validation on all webhook events</li>



<li>No card storage &#8211; Stripe handles all payment details</li>
</ul>
</li>



<li>Secret Management
<ul class="wp-block-list">
<li>Rails credentials &#8211; All secrets in encrypted credentials.yml.enc</li>
</ul>
</li>



<li>XSS Prevention
<ul class="wp-block-list">
<li>Automatic HTML escaping</li>



<li>CSP headers &#8211; Content Security Policy blocks inline scripts</li>
</ul>
</li>



<li>Transport Security
<ul class="wp-block-list">
<li>HTTPS everywhere &#8211; All resources loaded over HTTPS</li>



<li>Secure cookies &#8211; Session cookies marked secure in production</li>



<li>HSTS headers &#8211; Forces HTTPS connections</li>
</ul>
</li>



<li>DoS Prevention
<ul class="wp-block-list">
<li>Job queues &#8211; Background processing prevents request timeouts</li>



<li>Priority queues &#8211; Paid users get separate high-priority queue</li>



<li>Rate limiting &#8211; Comprehensive rate limits across all endpoints</li>



<li>Query optimization &#8211; Indexed queries prevent slow lookups</li>
</ul>
</li>
</ol>



<h2 class="wp-block-heading">Try it</h2>



<p>Demo (no signup): <a href="https://clausyapp.com/contracts/new?demo=hn">https://clausyapp.com/contracts/new?demo=hn</a></p>



<p>Full app: <a href="https://clausyapp.com">https://clausyapp.com</a></p>



<p>It&#8217;s not legal advice – I&#8217;m very explicit about that – but it can help you spot things you might want to ask a lawyer about.</p>
]]></content:encoded>
					
					<wfw:commentRss>https://blog.adamzolo.com/building-clausy-a-contract-analysis-tool-with-rails-8-and-claude-ai/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
		<item>
		<title>How We Fixed the &#8220;First Web Container is Unhealthy&#8221; Error: A DNS Deep Dive</title>
		<link>https://blog.adamzolo.com/how-we-fixed-the-first-web-container-is-unhealthy-error-a-dns-deep-dive/</link>
					<comments>https://blog.adamzolo.com/how-we-fixed-the-first-web-container-is-unhealthy-error-a-dns-deep-dive/#respond</comments>
		
		<dc:creator><![CDATA[Adam Zolo]]></dc:creator>
		<pubDate>Mon, 26 Jan 2026 16:10:56 +0000</pubDate>
				<category><![CDATA[docker]]></category>
		<category><![CDATA[Linux]]></category>
		<category><![CDATA[Rails]]></category>
		<category><![CDATA[Uncategorized]]></category>
		<guid isPermaLink="false">https://blog.adamzolo.com/?p=1082</guid>

					<description><![CDATA[The Error That Nearly Broke Our Deployment Three hours into our Kamal deployment, we were stuck in a loop: ERROR Failed to boot web on {ip_address} INFO First web container is unhealthy on {ip_address}, not booting any other roles The container would start, but Kamal&#8217;s health check kept failing. After 30 seconds, Kamal would kill&#8230;<p><a class="more-link" href="https://blog.adamzolo.com/how-we-fixed-the-first-web-container-is-unhealthy-error-a-dns-deep-dive/" title="Continue reading &#8216;How We Fixed the &#8220;First Web Container is Unhealthy&#8221; Error: A DNS Deep Dive&#8217;">Continue reading <span class="meta-nav">&#8594;</span></a></p>]]></description>
										<content:encoded><![CDATA[<br />
<h2>The Error That Nearly Broke Our Deployment</h2>
<p>Three hours into our Kamal deployment, we were stuck in a loop:</p>
<pre><code>ERROR Failed to boot web on {ip_address}
  INFO First web container is unhealthy on {ip_address}, not booting any other roles</code></pre>
<p>The container would start, but Kamal&#8217;s health check kept failing. After 30 seconds, Kamal would kill the container<br />
   and retry, creating an endless loop.</p>
<p>We spent hours debugging deployment scripts, PostgreSQL configurations, and Rails settings. The fix turned out to<br />
  be much simpler: DNS configuration.</p>
<h2>The Root Cause: Broken DNS Resolution</h2>
<h3>What Was Happening</h3>
<p>When Kamal tried to verify container health, it performed this sequence:</p>
<ol>
<li>Container starts → my_app-web-abc123 boots</li>
<li>Traefik (Kamal proxy) tries to check /up endpoint</li>
<li>DNS lookup → Resolve my_app-web-abc123 to an IP address</li>
<li>Health check fails → DNS resolution times out or fails</li>
<li>Container killed → Kamal marks it as unhealthy</li>
</ol>
<h3>The DNS Failure</h3>
<p>The Traefik container&#8217;s /etc/resolv.conf showed:</p>
<pre><code>nameserver 127.0.0.53
  search members.linode.com
  options edns0 trust-ad ndots:0</code></pre>
<p><strong>Problem:</strong> 127.0.0.53 is the host&#8217;s systemd-resolved DNS server. It&#8217;s not accessible from inside<br />
  Docker containers!</p>
<p>When Traefik tried to resolve my_app-web-abc123:</p>
<ul>
<li>It queried 127.0.0.53 (systemd-resolved)</li>
<li>The query failed with &#8220;connection refused&#8221;</li>
<li>Health check failed</li>
<li>Container was killed</li>
</ul>
<h2>The Solution: Proper Docker DNS Configuration</h2>
<h3>What We Fixed</h3>
<p>We configured Docker&#8217;s DNS settings in <code>/etc/docker/daemon.json</code>:</p>
<pre><code>{
    "dns": ["127.0.0.11", "8.8.8.8", "1.1.1.1"]
  }</code></pre>
<h3>Why This Works</h3>
<p><strong>1. 127.0.0.11 (Docker&#8217;s Internal DNS) &#8211; First Priority</strong></p>
<ul>
<li>Resolves container hostnames automatically</li>
<li>Handles inter-container communication</li>
<li>Always available inside Docker networks</li>
</ul>
<p><strong>2. 8.8.8.8 (Google DNS) &#8211; Second Priority</strong></p>
<ul>
<li>Resolves external domains (APIs, gems, etc.)</li>
<li>Fast and reliable</li>
<li>Global infrastructure</li>
</ul>
<p><strong>3. 1.1.1.1 (Cloudflare DNS) &#8211; Third Priority</strong></p>
<ul>
<li>Privacy-focused external DNS</li>
<li>Backup if 8.8.8.8 fails</li>
<li>No query logging</li>
</ul>
<h3>How Docker Uses This</h3>
<p>Docker&#8217;s DNS resolution order:</p>
<ol>
<li>Try 127.0.0.11 (internal) → container names</li>
<li>If that fails → 8.8.8.8 (external) → domains</li>
<li>If that fails → 1.1.1.1 (external) → domains</li>
</ol>
<h2>The IPv4/IPv6 Issue</h2>
<p>While debugging, we discovered another subtle problem:</p>
<h3>The IPv6 Trap</h3>
<p>The server setup script used:</p>
<pre><code>SERVER_IP=$(curl -s ifconfig.me || echo "ip_address_goes_here")</code></pre>
<p><strong>Problem:</strong> ifconfig.me returned an IPv6 address:</p>
<pre><code>2600:3c03::...</code></pre>
<p>This IPv6 address was used in PostgreSQL&#8217;s pg_hba.conf:</p>
<pre><code>host my_app_production my_app_user 2600:3c03.../32 md5</code></pre>
<p>PostgreSQL had issues with this IPv6 address, causing authentication failures.</p>
<h3>The Fix</h3>
<p>Force IPv4 detection:</p>
<pre><code>SERVER_IP=$(curl -s -4 ifconfig.me || echo "ip_address_goes_here")</code></pre>
<p>The <code>-4</code> flag ensures we always get an IPv4 address, which PostgreSQL handles reliably.</p>
<h2>The PostgreSQL Network Isolation Issue</h2>
<h3>The Problem</h3>
<p>Kamal uses a separate Docker network (172.18.0.0/16) for containers, while PostgreSQL is on the host&#8217;s Docker<br />
  bridge network (172.17.0.0/16).</p>
<p>The firewall only allowed 172.17.0.0/16:</p>
<pre><code>5432/tcp  ALLOW  172.17.0.0/16</code></pre>
<h3>The Fix</h3>
<p>Add the Kamal network to both firewall and PostgreSQL config:</p>
<p><strong>Firewall (ufw):</strong></p>
<pre><code>sudo ufw allow from 172.18.0.0/16 to any port 5432</code></pre>
<p><strong>PostgreSQL (pg_hba.conf):</strong></p>
<pre><code>host my_app_production my_app_user 172.18.0.0/16 md5</code></pre>
<h2>Complete Fix in our setup script</h2>
<h3>IPv4 Fix </h3>
<pre><code>SERVER_IP=$(curl -s -4 ifconfig.me || echo "ip_address_goes_here")</code></pre>
<h3>Kamal Network Firewall Rule</h3>
<pre><code>sudo ufw allow from 172.18.0.0/16 to any port 5432</code></pre>
<h3>PostgreSQL Kamal Network Rule </h3>
<pre><code>host $DB_NAME $DB_USER 172.18.0.0/16 md5</code></pre>
<h3>Docker DNS Configuration </h3>
<pre><code>{
    "dns": ["127.0.0.11", "8.8.8.8", "1.1.1.1"]
  }</code></pre>
<h2>Key Takeaways</h2>
<ol>
<li><strong>DNS is Critical for Container Orchestration</strong>
<ul>
<li>Always configure Docker&#8217;s DNS properly</li>
<li>Include both internal and external DNS servers</li>
<li>Test DNS resolution from containers</li>
</ul>
</li>
<li><strong>Network Isolation Matters</strong>
<ul>
<li>Docker networks are isolated by default</li>
<li>PostgreSQL must allow connections from all Docker networks</li>
<li>Firewall rules must match</li>
</ul>
</li>
<li><strong>IPv4 vs IPv6 Can Break Things</strong>
<ul>
<li>PostgreSQL works better with IPv4</li>
<li>Force IPv4 when detecting server IPs</li>
<li>Test both IPv4 and IPv6 connectivity</li>
</ul>
</li>
<li><strong>Health Checks are Essential</strong>
<ul>
<li>The /up endpoint is critical for Kamal</li>
<li>DNS must work for health checks to succeed</li>
<li>Timeout settings matter (30s default)</li>
</ul>
</li>
</ol>
<h2>Troubleshooting DNS Issues</h2>
<p>If you encounter &#8220;First web container is unhealthy&#8221;:</p>
<ol>
<li><strong>Check Container Logs</strong><br />
  <code>docker logs my_app-web-abc123</code></li>
<li><strong>Check Traefik/Kamal Proxy Logs</strong><br />
  <code>docker logs kamal-proxy | grep -i healthcheck</code></li>
<li><strong>Test DNS Resolution</strong>
<pre><code># From inside Traefik container
  docker exec kamal-proxy getent hosts my_app-web-abc123
  docker exec kamal-proxy getent hosts google.com</code></pre>
</li>
<li><strong>Verify DNS Configuration</strong>
<pre><code># Check daemon.json
  cat /etc/docker/daemon.json

  # Check container's resolv.conf
  docker exec kamal-proxy cat /etc/resolv.conf</code></pre>
</li>
<li><strong>Check PostgreSQL Connectivity</strong>
<pre><code># From kamal network
  docker run --rm --network kamal postgres:16 psql \
    -h 172.17.0.1 -U my_app_user -d my_app_production -c "SELECT 1"</code></pre>
</li>
</ol>
<h2>Results</h2>
<p>After implementing all fixes:</p>
<ul>
<li><img src="https://s.w.org/images/core/emoji/17.0.2/72x72/2705.png" alt="✅" class="wp-smiley" style="height: 1em; max-height: 1em;" /> DNS resolution works (internal and external)</li>
<li><img src="https://s.w.org/images/core/emoji/17.0.2/72x72/2705.png" alt="✅" class="wp-smiley" style="height: 1em; max-height: 1em;" /> Health checks pass (Traefik can reach containers)</li>
<li><img src="https://s.w.org/images/core/emoji/17.0.2/72x72/2705.png" alt="✅" class="wp-smiley" style="height: 1em; max-height: 1em;" /> PostgreSQL connections work (from both Docker networks)</li>
<li><img src="https://s.w.org/images/core/emoji/17.0.2/72x72/2705.png" alt="✅" class="wp-smiley" style="height: 1em; max-height: 1em;" /> Deployments succeed (consistent, reliable)</li>
<li><img src="https://s.w.org/images/core/emoji/17.0.2/72x72/2705.png" alt="✅" class="wp-smiley" style="height: 1em; max-height: 1em;" /> IPv4 detection works (no IPv6 issues)</li>
</ul>
<h2>Final Thoughts</h2>
<p>The &#8220;First web container is unhealthy&#8221; error can be a DNS configuration issue, not a deployment or application<br />
  problem.</p>
<p>By understanding how Docker networks work, how DNS resolution functions, and how PostgreSQL authentication works, we can prevent this issue from ever occurring again.</p>
<p><strong>Key files to review:</strong></p>
<ul>
<li><code>/etc/docker/daemon.json</code> &#8211; Docker DNS configuration</li>
<li><code>/etc/postgresql/16/main/pg_hba.conf</code> &#8211; PostgreSQL authentication</li>
<li><code>/etc/ufw/rules.conf</code> &#8211; Firewall rules</li>
</ul>
<p>The fix is now automated in our setup script, ensuring new servers have proper DNS and network configuration from<br />
  day one.</p>
]]></content:encoded>
					
					<wfw:commentRss>https://blog.adamzolo.com/how-we-fixed-the-first-web-container-is-unhealthy-error-a-dns-deep-dive/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
		<item>
		<title>Rails Migration to Change string to boolean (PostgreSQL)</title>
		<link>https://blog.adamzolo.com/rails-migration-to-change-string-to-boolean-postgresql/</link>
					<comments>https://blog.adamzolo.com/rails-migration-to-change-string-to-boolean-postgresql/#respond</comments>
		
		<dc:creator><![CDATA[Adam Zolo]]></dc:creator>
		<pubDate>Fri, 19 Jan 2024 20:47:21 +0000</pubDate>
				<category><![CDATA[Rails]]></category>
		<category><![CDATA[SQL]]></category>
		<guid isPermaLink="false">https://blog.adamzolo.com/?p=1057</guid>

					<description><![CDATA[When you run the migration to change the the column type from string to boolean, you may encounter this kind of error: This just tells you that you need a rule to convert your string to boolean. You can fix with using synthax. For example, if you want all columns to change to false: Or&#8230;<p><a class="more-link" href="https://blog.adamzolo.com/rails-migration-to-change-string-to-boolean-postgresql/" title="Continue reading &#8216;Rails Migration to Change string to boolean (PostgreSQL)&#8217;">Continue reading <span class="meta-nav">&#8594;</span></a></p>]]></description>
										<content:encoded><![CDATA[
<p>When you run the migration to change the the column type from string to boolean, you may encounter this kind of error:</p>



<pre class="wp-block-code"><code>PG::DatatypeMismatch: ERROR:  column "blah" cannot be cast automatically to type boolean
HINT:  You might need to specify "USING blah::boolean".</code></pre>



<p>This just tells you that you need a rule to convert your string to boolean. You can fix with <code>using</code> synthax. For example, if you want all columns to change to false:</p>



<pre class="wp-block-code"><code>change_table :table_name do |t|
  t.change :column_name, :boolean, using: 'false', default: false, null: false
end</code></pre>



<p>Or if you want to convert your existing values from your column, you could do something like this:</p>



<pre class="wp-block-code"><code>change_table :table_name do |t|
  t.change :column_name, :boolean, using: 'cast(column_name as boolean)', default: false, null: false
end</code></pre>
]]></content:encoded>
					
					<wfw:commentRss>https://blog.adamzolo.com/rails-migration-to-change-string-to-boolean-postgresql/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
		<item>
		<title>Proxy Sentry JS requests to the self-hosted server behind a firewall</title>
		<link>https://blog.adamzolo.com/proxy-sentry-js-requests-to-the-self-hosted-server-behind-a-firewall/</link>
					<comments>https://blog.adamzolo.com/proxy-sentry-js-requests-to-the-self-hosted-server-behind-a-firewall/#respond</comments>
		
		<dc:creator><![CDATA[Adam Zolo]]></dc:creator>
		<pubDate>Fri, 23 Oct 2020 18:48:51 +0000</pubDate>
				<category><![CDATA[Rails]]></category>
		<category><![CDATA[Ruby]]></category>
		<guid isPermaLink="false">http://blog.adamzolo.com/?p=950</guid>

					<description><![CDATA[Tech: Rails Problem: you have a self-hosted Sentry server behind a firewall and you want to report your frontend errors. One way to accomplish it is by modifying Sentry dsn to send it to your backend and then proxying them to the Sentry server. First, let&#8217;s set up a new route: It has to follow&#8230;<p><a class="more-link" href="https://blog.adamzolo.com/proxy-sentry-js-requests-to-the-self-hosted-server-behind-a-firewall/" title="Continue reading &#8216;Proxy Sentry JS requests to the self-hosted server behind a firewall&#8217;">Continue reading <span class="meta-nav">&#8594;</span></a></p>]]></description>
										<content:encoded><![CDATA[
<p>Tech: Rails</p>



<p>Problem: you have a self-hosted Sentry server behind a firewall and you want to report your frontend errors.</p>



<p>One way to accomplish it is by modifying Sentry dsn to send it to your backend and then proxying them to the Sentry server.</p>



<p>First, let&#8217;s set up a new route:</p>


<div class="wp-block-syntaxhighlighter-code "><pre class="brush: ruby; title: ; notranslate">
post &#039;frontend_errors/api/:project_id/store&#039;, to: &#039;frontend_errors#create&#039;
</pre></div>


<p>It has to follow a specific pattern to work with the Sentry frontend library. The only thing you can change in the above is <code>frontend_errors</code> &#8211; pick whatever name you want. The code above will expect you to have a FrontendErrorsController.</p>



<p>Now, the FrontEndErrorsController needs to redirect to your actual Sentry server in the format that Sentry expects. Let&#8217;s create a new class to handle it:</p>


<div class="wp-block-syntaxhighlighter-code "><pre class="brush: ruby; title: ; notranslate">
class SentryProxy
  # This could be different based on your Sentry version.
  # Look into raven-sentry gem codebase if this doesn&#039;t work
  # Look for http_transport.rb files - https://github.com/getsentry/sentry-ruby/blob/f6625bd12fa5ef86e4ce6a1515e8a8171cea9ece/sentry-ruby/lib/sentry/transport/http_transport.rb
  PROTOCOL_VERSION = &#039;5&#039;
  USER_AGENT = &quot;raven-ruby/#{Raven::VERSION}&quot;

  def initialize(body:, sentry_dsn:)
    @body = body
    @sentry_dsn = sentry_dsn
  end

  def post_to_sentry
    return if @sentry_dsn.blank?

    sentry_connection.post do |faraday|
      faraday.body = @body
    end
  end

  private

  def sentry_connection
    Faraday.new(url: sentry_post_url) do |faraday|
      faraday.headers&#x5B;&#039;X-Sentry-Auth&#039;] = generate_auth_header
      faraday.headers&#x5B;:user_agent] = &quot;sentry-ruby/#{Raven::VERSION}&quot;
      faraday.adapter(Faraday.default_adapter)
    end
  end

  def sentry_post_url
    key, url = @sentry_dsn.split(&#039;@&#039;)
    path, project_id = url.split(&#039;/&#039;)
    http_prefix, _keys = key.split(&#039;//&#039;)

    &quot;#{http_prefix}//#{path}/api/#{project_id}/store/&quot;
  end

  def generate_auth_header
    now = Time.now.to_i.to_s
    public_key, secret_key = @sentry_dsn.split(&#039;//&#039;).second.split(&#039;@&#039;).first.split(&#039;:&#039;)

    fields = {
      &#039;sentry_version&#039; =&gt; PROTOCOL_VERSION,
      &#039;sentry_client&#039; =&gt; USER_AGENT,
      &#039;sentry_timestamp&#039; =&gt; now,
      &#039;sentry_key&#039; =&gt; public_key,
      &#039;sentry_secret&#039; =&gt; secret_key
    }
    &#039;Sentry &#039; + fields.map { |key, value| &quot;#{key}=#{value}&quot; }.join(&#039;, &#039;)
  end
end
</pre></div>


<p>Now in your controller you can call it like this (assumes you can get your sentry_dsn on the backend):</p>


<div class="wp-block-syntaxhighlighter-code "><pre class="brush: ruby; title: ; notranslate">
def create
  SentryProxy.new(body: request.body.read, sentry_dsn: sentry_dsn).post_to_sentry

  head(:no_content)
end
</pre></div>


<p>And to make sure your frontend is properly configured, first import Sentry frontend libraries, then initialize them using:</p>


<div class="wp-block-syntaxhighlighter-code "><pre class="brush: ruby; title: ; notranslate">
 Sentry.init({
    dsn: `${window.location.protocol}//public_key@${window.location.host}/frontend_errors/0`});
</pre></div>


<p><code>public_key</code> is supposed to be&#8230; your public key. You have to supply it in the dsn even if you&#8217;re getting the dsn key on the backend, otherwise, the Sentry frontend library will throw errors. 0 is the project id &#8211; the same idea, you have to supply it for the Sentry frontend to properly parse it. It doesn&#8217;t have to be real, as we&#8217;re reconstructing the Sentry url on the backend, and you can get proper keys/project id on the backend.</p>



<p>This should do it. Now you can configure Sentry frontend library to capture all errors, capture specific exceptions or messages.</p>
]]></content:encoded>
					
					<wfw:commentRss>https://blog.adamzolo.com/proxy-sentry-js-requests-to-the-self-hosted-server-behind-a-firewall/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
		<item>
		<title>Using the same redis instance for Rails cache and non-cache entries</title>
		<link>https://blog.adamzolo.com/using-the-same-redis-instance-for-rails-cache-and-non-cache-entries/</link>
					<comments>https://blog.adamzolo.com/using-the-same-redis-instance-for-rails-cache-and-non-cache-entries/#respond</comments>
		
		<dc:creator><![CDATA[Adam Zolo]]></dc:creator>
		<pubDate>Fri, 16 Oct 2020 16:05:25 +0000</pubDate>
				<category><![CDATA[Rails]]></category>
		<category><![CDATA[Ruby]]></category>
		<guid isPermaLink="false">http://blog.adamzolo.com/?p=947</guid>

					<description><![CDATA[Redis docs: https://redis.io/topics/lru-cache OS: Ubuntu 18.04 LTS When you need to use redis for cache and non-cache entries (e.g., ActionCable, Sidekiq&#8230;), the recommended approach is to create a separate redis instance. However, if you want a simpler setup, or just can&#8217;t get another instance for reasons, there is an option to use the same redis&#8230;<p><a class="more-link" href="https://blog.adamzolo.com/using-the-same-redis-instance-for-rails-cache-and-non-cache-entries/" title="Continue reading &#8216;Using the same redis instance for Rails cache and non-cache entries&#8217;">Continue reading <span class="meta-nav">&#8594;</span></a></p>]]></description>
										<content:encoded><![CDATA[
<p>Redis docs: <a rel="noreferrer noopener" href="https://redis.io/topics/lru-cache" target="_blank">https://redis.io/topics/lru-cache</a></p>



<p>OS: Ubuntu 18.04 LTS</p>



<p>When you need to use redis for cache and non-cache entries (e.g., ActionCable, Sidekiq&#8230;), the recommended approach is to create a separate redis instance. However, if you want a simpler setup, or just can&#8217;t get another instance for reasons, there is an option to use the same redis instance for multiple uses.</p>



<p>We need to make sure that Redis will not evict our important data (e.g., Sidekiq), while at the same time evicting old cache entries. We could use any of the volatile eviction policies:</p>



<ul class="wp-block-list"><li>volatile-lru&nbsp;&#8211; remove least recently used keys where expiry is set</li><li>volatile-random &#8211; removes keys at random where expiry is set</li><li>volatile-ttl&nbsp;&#8211; evict keys with an&nbsp;<strong>expire set</strong>, and try to evict keys with a shorter time to live (TTL) first</li><li>volatile-lfu (starting with Redis 4.0) &#8211; evict using approximated LFU among the keys with an expire set.</li></ul>



<p>To set up the eviction policy on your redis instance, edit your <code>/etc/systemd/system/redis.conf</code> and set these parameters:</p>


<div class="wp-block-syntaxhighlighter-code "><pre class="brush: plain; title: ; notranslate">
maxmemory 100mb
maxmemory-policy volatile-lfu
</pre></div>


<p>Then in your Rails config update your store to use redis cache store, if not using already:</p>


<div class="wp-block-syntaxhighlighter-code "><pre class="brush: plain; title: ; notranslate">
  config.cache_store = :redis_cache_store, {
    url: ENV.fetch(&#039;REDIS_URL&#039;, &#039;redis://localhost:6379&#039;),
    expires_in: 24.hours
  }
</pre></div>


<p></p>
]]></content:encoded>
					
					<wfw:commentRss>https://blog.adamzolo.com/using-the-same-redis-instance-for-rails-cache-and-non-cache-entries/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
		<item>
		<title>GPG Key Encryption in Ruby/Rails</title>
		<link>https://blog.adamzolo.com/gpg-key-encryption-in-ruby-rails/</link>
					<comments>https://blog.adamzolo.com/gpg-key-encryption-in-ruby-rails/#respond</comments>
		
		<dc:creator><![CDATA[Adam Zolo]]></dc:creator>
		<pubDate>Thu, 27 Aug 2020 15:36:39 +0000</pubDate>
				<category><![CDATA[Rails]]></category>
		<category><![CDATA[Ruby]]></category>
		<guid isPermaLink="false">http://blog.adamzolo.com/?p=939</guid>

					<description><![CDATA[To import the public key in ruby: To encrypt data with a public key for a given recipient:]]></description>
										<content:encoded><![CDATA[
<p>To import the public key in ruby:</p>


<div class="wp-block-syntaxhighlighter-code "><pre class="brush: ruby; title: ; notranslate">
EncryptionError = Class.new(StandardError)

result, stderr, status = Open3.capture3(&quot;gpg --import #{@key_path}&quot;)
raise EncryptionError.new(stderr_data) unless status.success?
</pre></div>


<p>To encrypt data with a public key for a given recipient:</p>


<div class="wp-block-syntaxhighlighter-code "><pre class="brush: ruby; title: ; notranslate">
pgp_encrypt_command = &quot;gpg -ear #{recipient} --always-trust --trust-model always --local-user #{recipient} --default-key #{recipient}&quot;

encrypted_data, stderr_data, status = Open3.capture3(pgp_encrypt_command, stdin_data: data)
    raise EncryptionError.new(stderr_data) unless status.success?
</pre></div>]]></content:encoded>
					
					<wfw:commentRss>https://blog.adamzolo.com/gpg-key-encryption-in-ruby-rails/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
		<item>
		<title>Using Azurite with Active Storage</title>
		<link>https://blog.adamzolo.com/using-azurite-with-active-storage/</link>
					<comments>https://blog.adamzolo.com/using-azurite-with-active-storage/#respond</comments>
		
		<dc:creator><![CDATA[Adam Zolo]]></dc:creator>
		<pubDate>Tue, 02 Jun 2020 19:57:22 +0000</pubDate>
				<category><![CDATA[Active Storage]]></category>
		<category><![CDATA[Rails]]></category>
		<category><![CDATA[Ruby]]></category>
		<category><![CDATA[Azure]]></category>
		<category><![CDATA[Azurite]]></category>
		<guid isPermaLink="false">http://blog.adamzolo.com/?p=919</guid>

					<description><![CDATA[Install Azurite in your preferred way: npm install azurite Install Microsoft Azure Storage Explorer Create some directory to run azurite from: `~/azurite` Add storage.yml configuration for azurite (using the default dev account and key): Update development.rb to use azurite_emulator: Start azurite from the directory you created for azurite: azurite --location ~/azurite --debug ~/azurite/debug.log Start Azure&#8230;<p><a class="more-link" href="https://blog.adamzolo.com/using-azurite-with-active-storage/" title="Continue reading &#8216;Using Azurite with Active Storage&#8217;">Continue reading <span class="meta-nav">&#8594;</span></a></p>]]></description>
										<content:encoded><![CDATA[
<p>Install <a href="https://docs.microsoft.com/en-us/azure/storage/common/storage-use-azurite" target="_blank" rel="noreferrer noopener">Azurite</a> in your preferred way: <code>npm install azurite</code></p>



<p>Install <a href="https://azure.microsoft.com/en-us/features/storage-explorer/" target="_blank" rel="noreferrer noopener">Microsoft Azure Storage Explorer</a></p>



<p>Create some directory to run azurite from: `~/azurite`</p>



<p>Add <code>storage.yml</code> configuration for azurite (using the default dev account and key):</p>


<div class="wp-block-syntaxhighlighter-code "><pre class="brush: yaml; title: ; notranslate">
azurite_emulator:
  service: AzureStorage
  storage_account_name: &#039;devstoreaccount1&#039;
  storage_access_key: &#039;Eby8vdM02xNOcqFlqUwJPLlmEtlCDXJ1OUzFT50uSRZ6IFsuFq2UVErCz4I6tq/K1SZFPTOtr/KBHBeksoGMGw==&#039;
  container: &#039;container-name&#039;
  storage_blob_host: &#039;http://127.0.0.1:10000/devstoreaccount1&#039;
</pre></div>


<p></p>



<p>Update <code>development.rb</code> to use azurite_emulator: </p>


<div class="wp-block-syntaxhighlighter-code "><pre class="brush: ruby; title: ; notranslate">
config.active_storage.service = :azurite_emulator
</pre></div>


<p></p>



<p>Start azurite from the directory you created for azurite:  <code>azurite --location ~/azurite --debug ~/azurite/debug.log</code></p>



<p>Start Azure Storage Explorer, connect to local emulator, and create <code>container-name</code> blob container &#8211; the same container name you specified in the <code>storage.yml</code> file.</p>



<p>Start uploading to Azurite.</p>



<h2 class="wp-block-heading">Note for Rails 5.2</h2>



<p>Some changes have not been backported as of this post, and you have to monkey-patch ActiveStorage file as described here &#8211; <a href="http://www.garytaylor.blog/index.php/2019/01/30/rails-active-storage-and-azure-beyond-config/">http://www.garytaylor.blog/index.php/2019/01/30/rails-active-storage-and-azure-beyond-config/</a> &#8211; this allows us to work with azurite locally.</p>



<p></p>



<p>If you want to use the newer <code>azure-storage-blob</code> instead of the deprecated <code>azure-storage</code> and you&#8217;re on Rails 5.2, you have to do a bit more monkey-patching &#8211; otherwise, you&#8217;ll start getting <a href="https://stackoverflow.com/questions/62045971/no-such-file-to-load-azure-storage-rb">No such file to load — azure/storage.rb</a>&#8220;:</p>



<p>Add two empty files: <code>lib/azure/storage/core/auth/shared_access_signature.rb</code>, and <code>lib/azure/storage.rb</code></p>



<p>Add this to config/initializers/active_storage_6_patch.rb (this is the current master version of the ActiveStorage module):</p>


<div class="wp-block-syntaxhighlighter-code "><pre class="brush: ruby; title: ; notranslate">
require &quot;azure/storage/blob&quot;
require &#039;active_storage/service/azure_storage_service&#039;
module ActiveStorage
  # Wraps the Microsoft Azure Storage Blob Service as an Active Storage service.
  # See ActiveStorage::Service for the generic API documentation that applies to all services.
  class Service::AzureStorageService &lt; Service
    attr_reader :client, :container, :signer

    def initialize(storage_account_name:, storage_access_key:, container:, public: false, **options)
      @client = Azure::Storage::Blob::BlobService.create(storage_account_name: storage_account_name, storage_access_key: storage_access_key, **options)
      @signer = Azure::Storage::Common::Core::Auth::SharedAccessSignature.new(storage_account_name, storage_access_key)
      @container = container
      @public = public
    end

    def upload(key, io, checksum: nil, filename: nil, content_type: nil, disposition: nil, **)
      instrument :upload, key: key, checksum: checksum do
        handle_errors do
          content_disposition = content_disposition_with(filename: filename, type: disposition) if disposition &amp;&amp; filename

          client.create_block_blob(container, key, IO.try_convert(io) || io, content_md5: checksum, content_type: content_type, content_disposition: content_disposition)
        end
      end
    end

    def download(key, &amp;block)
      if block_given?
        instrument :streaming_download, key: key do
          stream(key, &amp;block)
        end
      else
        instrument :download, key: key do
          handle_errors do
            _, io = client.get_blob(container, key)
            io.force_encoding(Encoding::BINARY)
          end
        end
      end
    end

    def download_chunk(key, range)
      instrument :download_chunk, key: key, range: range do
        handle_errors do
          _, io = client.get_blob(container, key, start_range: range.begin, end_range: range.exclude_end? ? range.end - 1 : range.end)
          io.force_encoding(Encoding::BINARY)
        end
      end
    end

    def delete(key)
      instrument :delete, key: key do
        client.delete_blob(container, key)
      rescue Azure::Core::Http::HTTPError =&gt; e
        raise unless e.type == &quot;BlobNotFound&quot;
        # Ignore files already deleted
      end
    end

    def delete_prefixed(prefix)
      instrument :delete_prefixed, prefix: prefix do
        marker = nil

        loop do
          results = client.list_blobs(container, prefix: prefix, marker: marker)

          results.each do |blob|
            client.delete_blob(container, blob.name)
          end

          break unless marker = results.continuation_token.presence
        end
      end
    end

    def exist?(key)
      instrument :exist, key: key do |payload|
        answer = blob_for(key).present?
        payload&#x5B;:exist] = answer
        answer
      end
    end

    def url_for_direct_upload(key, expires_in:, content_type:, content_length:, checksum:)
      instrument :url, key: key do |payload|
        generated_url = signer.signed_uri(
          uri_for(key), false,
          service: &quot;b&quot;,
          permissions: &quot;rw&quot;,
          expiry: format_expiry(expires_in)
        ).to_s

        payload&#x5B;:url] = generated_url

        generated_url
      end
    end

    def headers_for_direct_upload(key, content_type:, checksum:, filename: nil, disposition: nil, **)
      content_disposition = content_disposition_with(type: disposition, filename: filename) if filename

      { &quot;Content-Type&quot; =&gt; content_type, &quot;Content-MD5&quot; =&gt; checksum, &quot;x-ms-blob-content-disposition&quot; =&gt; content_disposition, &quot;x-ms-blob-type&quot; =&gt; &quot;BlockBlob&quot; }
    end

    private
      def private_url(key, expires_in:, filename:, disposition:, content_type:, **)
        signer.signed_uri(
          uri_for(key), false,
          service: &quot;b&quot;,
          permissions: &quot;r&quot;,
          expiry: format_expiry(expires_in),
          content_disposition: content_disposition_with(type: disposition, filename: filename),
          content_type: content_type
        ).to_s
      end

      def public_url(key, **)
        uri_for(key).to_s
      end


      def uri_for(key)
        client.generate_uri(&quot;#{container}/#{key}&quot;)
      end

      def blob_for(key)
        client.get_blob_properties(container, key)
      rescue Azure::Core::Http::HTTPError
        false
      end

      def format_expiry(expires_in)
        expires_in ? Time.now.utc.advance(seconds: expires_in).iso8601 : nil
      end

      # Reads the object for the given key in chunks, yielding each to the block.
      def stream(key)
        blob = blob_for(key)

        chunk_size = 5.megabytes
        offset = 0

        raise ActiveStorage::FileNotFoundError unless blob.present?

        while offset &lt; blob.properties&#x5B;:content_length]
          _, chunk = client.get_blob(container, key, start_range: offset, end_range: offset + chunk_size - 1)
          yield chunk.force_encoding(Encoding::BINARY)
          offset += chunk_size
        end
      end

      def handle_errors
        yield
      rescue Azure::Core::Http::HTTPError =&gt; e
        case e.type
        when &quot;BlobNotFound&quot;
          raise ActiveStorage::FileNotFoundError
        when &quot;Md5Mismatch&quot;
          raise ActiveStorage::IntegrityError
        else
          raise
        end
      end
  end
end
</pre></div>]]></content:encoded>
					
					<wfw:commentRss>https://blog.adamzolo.com/using-azurite-with-active-storage/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
		<item>
		<title>An error occurred while installing nokogiri, and Bundler cannot continue&#8230;</title>
		<link>https://blog.adamzolo.com/an-error-occurred-while-installing-nokogiri-and-bundler-cannot-continue/</link>
					<comments>https://blog.adamzolo.com/an-error-occurred-while-installing-nokogiri-and-bundler-cannot-continue/#respond</comments>
		
		<dc:creator><![CDATA[Adam Zolo]]></dc:creator>
		<pubDate>Sun, 25 Nov 2018 11:40:01 +0000</pubDate>
				<category><![CDATA[Rails]]></category>
		<category><![CDATA[Ruby]]></category>
		<guid isPermaLink="false">http://blog.adamzolo.com/?p=792</guid>

					<description><![CDATA[This is only one of the reasons why this may happen &#8211; Xcode Command Line Tools (CLT) are not installed. This may happen after you upgrade you macOS version. To fix, run this on the command line: this should trigger a popup with the invitation to install Xcode CLT.]]></description>
										<content:encoded><![CDATA[<p>This is only one of the reasons why this may happen &#8211; Xcode Command Line Tools (CLT) are not installed. This may happen after you upgrade you macOS version.</p>
<p>To fix, run this on the command line:</p>
<pre class="brush: plain; title: ; notranslate">
xcode-select --install
</pre>
<p>this should trigger a popup with the invitation to install Xcode CLT.</p>
]]></content:encoded>
					
					<wfw:commentRss>https://blog.adamzolo.com/an-error-occurred-while-installing-nokogiri-and-bundler-cannot-continue/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
	</channel>
</rss>
