<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0"><channel><title><![CDATA[Sina Rezaei]]></title><description><![CDATA[Sina Rezaei]]></description><link>https://sinarezaei.hashnode.dev</link><generator>RSS for Node</generator><lastBuildDate>Tue, 17 Nov 2026 03:37:11 GMT</lastBuildDate><atom:link href="https://sinarezaei.hashnode.dev/rss.xml" rel="self" type="application/rss+xml"/><language><![CDATA[en]]></language><ttl>60</ttl><item><title><![CDATA[Your AI Pentester Found an SSRF. Can It Reproduce the Attack?]]></title><description><![CDATA[The first scan found an SSRF. The second one didn't. I wouldn't close the finding just yet. The endpoint accepts a URL, fetches the resource, and returns…]]></description><link>https://sinarezaei.hashnode.dev/your-ai-pentester-found-an-ssrf-can-it-reproduce-the-attack</link><guid isPermaLink="true">https://sinarezaei.hashnode.dev/your-ai-pentester-found-an-ssrf-can-it-reproduce-the-attack</guid><category><![CDATA[cybersecurity]]></category><category><![CDATA[websecurity]]></category><category><![CDATA[AI]]></category><category><![CDATA[ssrf ]]></category><dc:creator><![CDATA[Sina Rezaei]]></dc:creator><pubDate>Fri, 30 Oct 2026 00:25:59 GMT</pubDate><enclosure url="https://cdn.hashnode.com/uploads/covers/6ac792875f5e138fe84f61ac/833492cb-e699-4d62-b606-acef86fbc720.jpg" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>The first scan found an SSRF. The second one didn't.</p>
<p>I wouldn't close the finding just yet.</p>
<p>The endpoint accepts a URL, fetches the resource, and returns its response. During the first scan, the agent managed to follow a redirect and reach an internal service. It reported the issue with a successful response as evidence.</p>
<p>Then it ran the test again. Same endpoint, same application. No SSRF.</p>
<p>One thing I'd check before looking at the model's reasoning is the actual network traffic.</p>
<p>Suppose the agent tests a hostname that resolves to a public IP. The application checks the address and allows the request. But there's a gap between that check and the connection itself. If another DNS resolution returns a private IP, the application could end up connecting somewhere the original validation was supposed to block.</p>
<p>That's the DNS rebinding problem.</p>
<p>The details depend on the HTTP client, DNS caching, connection reuse, and whether a proxy is involved. A second lookup isn't guaranteed. But if the component making the connection doesn't enforce the destination restrictions, checking the hostname at the beginning isn't enough.</p>
<p>Redirects make this more interesting. The first URL can point to a public host and return a redirect to another hostname. If the application validates only the original destination, the next request may escape the intended boundary. OWASP recommends disabling automatic redirect following in the HTTP client to avoid this validation bypass. If redirects are required, each destination needs to be checked before the next request is made.</p>
<p>I'd want to see the actual destination IP at connection time, not just the hostname supplied by the agent. I'd also check whether outbound network rules prevent access to internal address ranges.</p>
<p>There's a second problem here, and it has less to do with SSRF itself.</p>
<p>Even if the agent sends exactly the same request twice, the network path might not be identical. DNS can return a different address, a redirect target can change, or the HTTP client can reuse an existing connection in one run and establish a new one in the next.</p>
<p>Looking at the final model response won't tell us which of these happened.</p>
<p>For this kind of test, I'd keep the raw request, DNS answers, redirect history, destination IP, response status, and target build identifier for each run. Not just the agent's summary. Without that information, a failed second scan doesn't tell us whether the vulnerability disappeared or the request simply took another route.</p>
<p>There's also a difference between replaying a previous execution and reproducing the vulnerability. Replaying saved tool calls can reconstruct what the agent did before. It doesn't prove that the current application is still vulnerable.</p>
<p>That's why I'd avoid treating a second scan that returns nothing as evidence that the issue is gone.</p>
<p>Before closing the finding, I'd want to know one thing:</p>
<p><strong>Did the application stop accepting the request, or did the request stop reaching the same destination?</strong></p>
<hr />
<p><strong>Reference</strong></p>
<ul>
<li><a href="https://cheatsheetseries.owasp.org/cheatsheets/Server_Side_Request_Forgery_Prevention_Cheat_Sheet.html">OWASP: Server-Side Request Forgery Prevention Cheat Sheet</a></li>
</ul>
]]></content:encoded></item><item><title><![CDATA[The SQL NOT IN Trap: When NULL Quietly Breaks Your Query]]></title><description><![CDATA[I've seen SQL bugs that are easy to miss because nothing actually crashes. The query runs, the database returns a result, and the code moves on. You only…]]></description><link>https://sinarezaei.hashnode.dev/the-sql-not-in-trap-when-null-quietly-breaks-your-query</link><guid isPermaLink="true">https://sinarezaei.hashnode.dev/the-sql-not-in-trap-when-null-quietly-breaks-your-query</guid><category><![CDATA[PostgreSQL]]></category><category><![CDATA[SQL]]></category><category><![CDATA[database]]></category><category><![CDATA[Software Engineering]]></category><dc:creator><![CDATA[Sina Rezaei]]></dc:creator><pubDate>Thu, 29 Oct 2026 11:58:52 GMT</pubDate><enclosure url="https://cdn.hashnode.com/uploads/covers/6ac792875f5e138fe84f61ac/fa28b288-bf13-4470-9d4e-203fb8f2584c.png" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>I've seen SQL bugs that are easy to miss because nothing actually crashes. The query runs, the database returns a result, and the code moves on. You only notice something is wrong when a cleanup job skips records it should have processed.</p>
<p><code>NOT IN</code> can cause exactly this kind of problem when <code>NULL</code> gets involved.</p>
<h2>The problem isn't where you'd expect</h2>
<p>Imagine you're cleaning up stale identity mappings in a multi-tenant platform.</p>
<p>You have a table of active memberships and another table that maps external identities to internal accounts. You want to find memberships that don't have a matching identity mapping.</p>
<p>A first attempt might look like this:</p>
<pre><code class="language-sql">SELECT m.tenant_id, m.external_id
FROM memberships m
WHERE m.external_id NOT IN (
    SELECT i.external_id
    FROM identity_mappings i
);
</code></pre>
<p>Looks reasonable. Find the external IDs that aren't in the mapping table.</p>
<p>Now imagine <code>identity_mappings.external_id</code> contains these values:</p>
<pre><code class="language-text">ext_1042
ext_2087
NULL
ext_3911
</code></pre>
<p>That <code>NULL</code> changes the result.</p>
<p>SQL doesn't treat <code>NULL</code> as an ordinary value. It represents an unknown value, so comparisons involving it can evaluate to <code>UNKNOWN</code> rather than <code>TRUE</code> or <code>FALSE</code>.</p>
<p>For a value that doesn't match any known ID, SQL can't establish that it differs from every value in the subquery because one of those values is unknown. The <code>NOT IN</code> condition therefore evaluates to <code>UNKNOWN</code>, and the <code>WHERE</code> clause filters the row out.</p>
<p>The query doesn't throw an error. It just returns fewer rows than you expected.</p>
<p>That's the part that makes this bug annoying to track down.</p>
<h2>Why changing the query isn't the whole fix</h2>
<p>A common alternative is <code>NOT EXISTS</code>:</p>
<pre><code class="language-sql">SELECT m.tenant_id, m.external_id
FROM memberships m
WHERE NOT EXISTS (
    SELECT 1
    FROM identity_mappings i
    WHERE i.external_id = m.external_id
);
</code></pre>
<p>This avoids the specific problem caused by an unrelated <code>NULL</code> in the subquery. The database checks whether a matching row exists instead of comparing the outer value against every result in a list.</p>
<p>But there's another issue hiding in the original query.</p>
<p>This is a multi-tenant system. The same external ID might legitimately exist in more than one tenant. If the relationship is defined by both <code>tenant_id</code> and <code>external_id</code>, comparing only the external ID is incomplete.</p>
<p>The query should reflect that:</p>
<pre><code class="language-sql">SELECT m.tenant_id, m.external_id
FROM memberships m
WHERE NOT EXISTS (
    SELECT 1
    FROM identity_mappings i
    WHERE i.tenant_id = m.tenant_id
      AND i.external_id = m.external_id
);
</code></pre>
<p>Now the query checks the relationship the system actually cares about.</p>
<p>There's still a decision to make about nullable external IDs. With the equality comparison above, a <code>NULL</code> external ID won't match another <code>NULL</code> external ID. If the business rules say those records should be treated as matching, the query needs different logic. If <code>NULL</code> means the identity hasn't been linked yet, treating it as unmatched might be exactly what you want.</p>
<p>That decision belongs in the data model and business rules, not in an assumption about how SQL will behave.</p>
<h2>The tests I'd add before running this in production</h2>
<p>For a cleanup job like this, I'd test more than a normal matching record and an orphaned record.</p>
<ul>
<li>A mapping exists for the same external ID and the same tenant.</li>
<li>The same external ID exists under a different tenant.</li>
<li>The mapping table contains a <code>NULL</code> external ID.</li>
<li>The membership itself has a <code>NULL</code> external ID.</li>
<li>Multiple mappings exist for the same tenant and external ID.</li>
</ul>
<p>I'd also check whether the database schema enforces the intended relationship. If <code>(tenant_id, external_id)</code> is supposed to identify a mapping uniquely, a suitable unique constraint may prevent inconsistent data from accumulating in the first place. Whether <code>external_id</code> should be nullable is a separate schema decision.</p>
<p>And before running a destructive cleanup, I'd inspect the candidate rows and verify the expected count. A query returning valid SQL results doesn't mean it's safe to delete everything it returns.</p>
<h2>The bigger lesson</h2>
<p><code>NOT IN</code> versus <code>NOT EXISTS</code> is worth understanding, but it's only one part of the problem.</p>
<p>A query can be syntactically valid and still describe the wrong relationship. It can handle <code>NULL</code> correctly and still cross tenant boundaries. It can pass tests built around clean data and fail as soon as production data gets messy.</p>
<p>When I review an anti-join, I want to know three things: what counts as a match, what <code>NULL</code> is supposed to mean, and which columns actually define the relationship.</p>
<p>The SQL comes after that.</p>
<p>Have you run into a query that looked correct in code review but turned out to be checking the wrong relationship?</p>
]]></content:encoded></item><item><title><![CDATA[How Much Coding Do You Really Need in the Age of AI?]]></title><description><![CDATA[I don't think learning to code is becoming pointless. I think the way we learn it is changing. You don't have to spend months memorizing syntax before…]]></description><link>https://sinarezaei.hashnode.dev/how-much-coding-do-you-really-need-in-the-age-of-ai</link><guid isPermaLink="true">https://sinarezaei.hashnode.dev/how-much-coding-do-you-really-need-in-the-age-of-ai</guid><category><![CDATA[General Programming]]></category><category><![CDATA[AI]]></category><category><![CDATA[webdev]]></category><category><![CDATA[Discuss]]></category><dc:creator><![CDATA[Sina Rezaei]]></dc:creator><pubDate>Sat, 24 Oct 2026 14:30:30 GMT</pubDate><enclosure url="https://cdn.hashnode.com/uploads/covers/6ac792875f5e138fe84f61ac/564872f0-de82-4348-a62c-e6d8a4c6850f.png" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>I don't think learning to code is becoming pointless. I think the way we learn it is changing.</p>
<p>You don't have to spend months memorizing syntax before building something useful. You can start a project, figure things out as you go, and learn from the problems you run into.</p>
<p>But there's one thing I wouldn't skip: understanding what's happening behind the code.</p>
<p>Imagine you're building a REST API with Python and FastAPI. It works fine during development, but once you deploy it and start handling more traffic, some endpoints become painfully slow.</p>
<p>The problem turns out to be a database query that loads thousands of records when the client only needs 20.</p>
<p>If you understand SQL, pagination, and indexing, you have a starting point. You can investigate the query, check the execution plan, and figure out what's actually causing the slowdown.</p>
<p>Without those fundamentals, you might keep changing the code without knowing whether you're fixing the problem or making it worse.</p>
<p>That's why I'd focus on learning how software works, not just how to write it.</p>
<p>Start with variables, functions, data structures, and error handling. Then move on to APIs, databases, testing, and debugging. As your projects grow, learn about architecture, performance, and security.</p>
<p>You don't need to master everything before building your first application. You just need enough knowledge to understand the code, question its behavior, and verify that it does what you expect.</p>
<p>And when you hit something unfamiliar, learn it when you need it.</p>
<h2>So, What's Enough?</h2>
<p>For me, it's the point where you can look at a piece of code and explain what it does, identify potential problems, and test whether the solution actually works.</p>
<p>You can always go deeper as your projects demand it.</p>
<p>The goal isn't to memorize every language feature. It's to understand software well enough to make good technical decisions.</p>
<p><strong>I'm curious where other developers draw the line. How much programming knowledge do you think is necessary to build reliable software today?</strong></p>
]]></content:encoded></item><item><title><![CDATA[All Tests Passed. The Expired Token Still Worked.]]></title><description><![CDATA[There's a dangerous kind of bug that doesn't crash the application, produce a stack trace, or turn your CI pipeline red. It simply lets something happen…]]></description><link>https://sinarezaei.hashnode.dev/all-tests-passed-the-expired-token-still-worked</link><guid isPermaLink="true">https://sinarezaei.hashnode.dev/all-tests-passed-the-expired-token-still-worked</guid><category><![CDATA[cybersecurity]]></category><category><![CDATA[SoftwareDevelopment]]></category><category><![CDATA[AI]]></category><category><![CDATA[Testing]]></category><dc:creator><![CDATA[Sina Rezaei]]></dc:creator><pubDate>Tue, 20 Oct 2026 08:16:28 GMT</pubDate><enclosure url="https://cdn.hashnode.com/uploads/covers/6ac792875f5e138fe84f61ac/ddfb097f-85b1-4a87-9b96-d8ef74fd8d19.png" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>There's a dangerous kind of bug that doesn't crash the application, produce a stack trace, or turn your CI pipeline red.</p>
<p>It simply lets something happen that should never have happened.</p>
<p>Imagine you're building an API with an AI coding agent. The agent implements JWT authentication, adds unit tests, runs the suite, and reports that everything passes.</p>
<p>You review the pull request. The middleware looks reasonable. The tests cover valid tokens, malformed tokens, and missing authorization headers.</p>
<p>You merge it.</p>
<p>A few days later, you discover that an expired token can still access a protected endpoint.</p>
<p>How did that get through a test suite that was supposedly checking authentication?</p>
<p>Let's look at the implementation.</p>
<h2>The bug isn't in the token format</h2>
<p>A JWT can have a valid signature and still be invalid for the current request.</p>
<p>For example, a token might have been signed correctly yesterday but expired ten minutes ago. Signature verification establishes that the token was issued by a trusted signer and hasn't been altered. It doesn't, by itself, establish that the token is still valid for use.</p>
<p>A simplified verification function might look like this:</p>
<pre><code class="language-javascript">function verifyAccessToken(token) {
  const payload = verifySignature(token);

  if (!payload) {
    throw new Error("Invalid token");
  }

  return payload;
}
</code></pre>
<p>The problem is that the function never checks the token's expiration claim.</p>
<p>Assuming <code>verifySignature()</code> verifies only the signature and doesn't validate expiration, a correctly signed but expired token can still be accepted.</p>
<p>A more complete implementation would validate the relevant claims:</p>
<pre><code class="language-javascript">function verifyAccessToken(token) {
  const payload = verifySignature(token);

  if (!payload) {
    throw new Error("Invalid token");
  }

  if (typeof payload.exp !== "number") {
    throw new Error("Missing expiration");
  }

  if (payload.exp &lt;= Math.floor(Date.now() / 1000)) {
    throw new Error("Token expired");
  }

  return payload;
}
</code></pre>
<p>This is still a simplified example. Production authentication should use a maintained JWT library configured to verify the allowed algorithm, signature, issuer, audience, expiration, and other claims required by the application. Hand-written verification code is not a substitute for that.</p>
<p>But the missing condition illustrates the problem.</p>
<p>The implementation can handle malformed tokens correctly while failing to enforce a critical security requirement.</p>
<h2>How could the tests still pass?</h2>
<p>Consider a test suite generated alongside the implementation:</p>
<pre><code class="language-javascript">describe("access token verification", () =&gt; {
  it("accepts a valid signed token", () =&gt; {
    expect(() =&gt; verifyAccessToken(validToken))
      .not.toThrow();
  });

  it("rejects an invalid token", () =&gt; {
    expect(() =&gt; verifyAccessToken("not-a-token"))
      .toThrow();
  });
});
</code></pre>
<p>Both tests can pass even though expiration is never checked.</p>
<p>The tests establish two facts: a particular valid token is accepted, and a malformed token is rejected.</p>
<p>They don't establish that an expired token is rejected.</p>
<p>That distinction matters because authentication is not a binary check between "valid signature" and "invalid signature." It is a set of independent security conditions.</p>
<p>A better test would construct a token with a valid signature and an expiration timestamp in the past, then assert that verification fails.</p>
<pre><code class="language-javascript">it("rejects a correctly signed but expired token", () =&gt; {
  const expiredToken = createSignedToken({
    sub: "user-123",
    exp: Math.floor(Date.now() / 1000) - 60
  });

  expect(() =&gt; verifyAccessToken(expiredToken))
    .toThrow();
});
</code></pre>
<p>Here, <code>createSignedToken()</code> is a test helper that signs the payload with a trusted test key. The test should run against the actual verification implementation, not a mock that already rejects expired tokens.</p>
<p>The key detail is that the signature remains valid. Only the expiration condition is violated.</p>
<p>That isolates the behavior we want to verify.</p>
<h2>The bigger issue is how the tests were created</h2>
<p>Now imagine asking an AI coding agent to implement authentication and generate tests for it.</p>
<p>The agent reads the implementation, identifies the obvious branches, and writes tests for valid and malformed tokens.</p>
<p>Everything passes.</p>
<p>But if the agent never identifies token expiration as an independent requirement, both the implementation and the tests can share the same blind spot.</p>
<p>This doesn't mean AI-generated tests are inherently bad. It means tests derived exclusively from an implementation can confirm its existing behavior without proving that the behavior is correct.</p>
<p>A 2026 experiment published on GitHub illustrates the distinction between conventional AI-generated tests, specification-based tests, and property-based tests. Its authors report finding date-handling defects that ordinary example-based tests missed.</p>
<p>The repository is an independent experiment rather than a peer-reviewed benchmark, so its results should be read in that context.</p>
<p><a href="https://github.com/choas/vibe-mutation-test">Explore the experiment and its test suites</a>.</p>
<p>The lesson is not that every test needs to be written manually. It's that the source of the expected behavior matters.</p>
<p>If the implementation defines the tests and the tests are then used to approve the implementation, the verification process can become circular.</p>
<h2>How I'd make the workflow harder to fool</h2>
<p>For security-sensitive code, I would separate the specification from the implementation.</p>
<p>First, define the required behavior:</p>
<ul>
<li><p>A correctly signed, unexpired token with valid claims is accepted.</p>
</li>
<li><p>An expired token is rejected.</p>
</li>
<li><p>A token with an invalid signature is rejected.</p>
</li>
<li><p>A token with a missing expiration claim is rejected if the application's policy requires it.</p>
</li>
<li><p>A token with the wrong issuer or audience is rejected.</p>
</li>
<li><p>A token that is valid cryptographically but lacks the required permission cannot access the protected resource.</p>
</li>
</ul>
<p>Then derive the tests from those requirements, rather than asking the coding agent to inspect its own implementation and decide what deserves testing.</p>
<p>I'd also introduce deliberate mutations.</p>
<p>For example, remove the expiration check from the implementation and run the test suite again.</p>
<p>If the suite remains green, it hasn't demonstrated that it protects expiration behavior.</p>
<p>This is where mutation testing can help. Instead of asking only whether the code passes, it asks whether the tests detect meaningful changes that should break the expected behavior.</p>
<p>For an authentication system, I'd additionally test the complete request path with an expired token and verify that the protected resource is never reached.</p>
<p>A unit test can prove that a verification function rejects a token. An integration test can establish that the API actually enforces that decision.</p>
<p>Both are useful, and neither should be confused with the other.</p>
<h2>Passing tests is not the same as proving security</h2>
<p>I don't think the solution is to stop using AI coding agents or to demand hundreds of tests for every function.</p>
<p>The better question is whether the tests are independent enough to challenge the implementation.</p>
<p>A thousand assertions about successful authentication don't necessarily protect against an expired token if none of them checks expiration.</p>
<p>And a high line-coverage percentage doesn't establish that every security requirement has been enforced.</p>
<p>For critical code, I'd rather have a small suite that tests the security contract than a huge suite that mostly confirms the happy path.</p>
<p>The same principle applies to authorization, payment processing, session management, data validation, and any other area where a missing condition can produce a serious consequence.</p>
<h2>Who should decide what correctness means?</h2>
<p>When an AI coding agent writes both the implementation and the tests, it can be tempting to treat a green CI pipeline as the final verdict.</p>
<p>But the pipeline only evaluates the conditions we've taught it to check.</p>
<p>If a security requirement is missing from those conditions, the software can pass every test and still violate the requirement.</p>
<p><strong>Here's my question for developers building with AI:</strong></p>
<p>Would you trust an AI coding agent to write and approve the tests for its own authentication implementation, or would you require an independent specification and security-focused test suite?</p>
<p>And if you already use AI-generated tests, what's your method for finding the bugs that those tests never thought to look for?</p>
<p>I'd be interested in practical examples, especially from teams working on APIs and production authentication systems.</p>
]]></content:encoded></item><item><title><![CDATA[Getting to Know Yourself: Understanding self in Ruby]]></title><description><![CDATA[Learn how self works in Ruby through objects, scope, and method context.]]></description><link>https://sinarezaei.hashnode.dev/getting-to-know-yourself-understanding-self-in-ruby</link><guid isPermaLink="true">https://sinarezaei.hashnode.dev/getting-to-know-yourself-understanding-self-in-ruby</guid><category><![CDATA[Metaprogramming ]]></category><category><![CDATA[Ruby]]></category><category><![CDATA[Rails]]></category><dc:creator><![CDATA[Sina Rezaei]]></dc:creator><pubDate>Thu, 08 Oct 2026 13:13:58 GMT</pubDate><enclosure url="https://cdn.hashnode.com/uploads/covers/6ac792875f5e138fe84f61ac/04963562-5e2a-4779-ad5c-cafb85c1f968.png" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p><code>self</code> is one of those Ruby keywords that looks easy until you meet it in real code.</p>
<p>You see it in a setter:</p>
<pre><code class="language-ruby">self.name = normalized_name
</code></pre>
<p>Then in a class method:</p>
<pre><code class="language-ruby">def self.from_cents(...)
</code></pre>
<p>Then somewhere inside a DSL or <code>instance_eval</code>, and suddenly the question isn't really:</p>
<blockquote>
<p>What does <code>self</code> mean?</p>
</blockquote>
<p>The better question is:</p>
<blockquote>
<p><strong>Who is</strong> <code>self</code> <strong>right here?</strong></p>
</blockquote>
<p>That small change makes Ruby's object model much easier to follow.</p>
<h2>The setter case is where it starts to matter</h2>
<p>Consider a model-like object:</p>
<pre><code class="language-ruby">class Customer
  attr_accessor :name, :email

  def initialize(name:, email:)
    @name = name
    @email = email
  end

  def normalize
    self.name = name.strip.downcase
    self.email = email.strip.downcase
  end

  def contact
    "#{name} &lt;#{email}&gt;"
  end
end

customer = Customer.new(
  name: "Maya",
  email: "MAYA@EXAMPLE.COM "
)

customer.normalize

puts customer.contact
</code></pre>
<p>There is something easy to miss here:</p>
<pre><code class="language-ruby">self.name = name.strip.downcase
</code></pre>
<p>Why not:</p>
<pre><code class="language-ruby">name = name.strip.downcase
</code></pre>
<p>Because those two lines are doing different things.</p>
<p>The second one is a local variable assignment.</p>
<p>The first one calls the <code>name=</code> setter on the current object.</p>
<p>Ruby lets us call the getter without explicitly writing the receiver:</p>
<pre><code class="language-ruby">name
</code></pre>
<p>But assignment creates an ambiguity. When we write:</p>
<pre><code class="language-ruby">self.name = ...
</code></pre>
<p>we are making the receiver explicit.</p>
<p>In other words:</p>
<pre><code class="language-ruby">self.name = "Maya"
</code></pre>
<p>means:</p>
<blockquote>
<p>Call <code>name=</code> on the object I'm currently working with.</p>
</blockquote>
<p>That object is <code>self</code>.</p>
<p>And notice something important.</p>
<p>We didn't create <code>self</code>.</p>
<p>We didn't assign it.</p>
<p>Ruby already knew what <code>self</code> was when <code>normalize</code> started running.</p>
<p>That is the first useful clue.</p>
<p><code>self</code> is less about a special keyword and more about <strong>the object currently receiving the work</strong>.</p>
<h2>Most of the time, Ruby hides it from you</h2>
<p>Take a slightly more realistic object:</p>
<pre><code class="language-ruby">class Invoice
  def initialize(customer, total)
    @customer = customer
    @total = total
    @status = :open
  end

  def close
    return false unless valid_for_closing?

    mark_as_paid
    notify_customer
    true
  end

  private

  def valid_for_closing?
    @total.positive? &amp;&amp; @status == :open
  end

  def mark_as_paid
    @status = :paid
  end

  def notify_customer
    puts "Invoice notification sent to #{@customer}"
  end
end
</code></pre>
<p>Inside <code>close</code>, Ruby sees:</p>
<pre><code class="language-ruby">mark_as_paid
notify_customer
</code></pre>
<p>You could make the receiver explicit:</p>
<pre><code class="language-ruby">self.mark_as_paid
self.notify_customer
</code></pre>
<p>But normally there is no reason to.</p>
<p>The receiver is already there.</p>
<p>It is <code>self</code>.</p>
<p>So when Ruby evaluates:</p>
<pre><code class="language-ruby">mark_as_paid
</code></pre>
<p>the useful mental model is:</p>
<pre><code class="language-ruby">self.mark_as_paid
</code></pre>
<p>The receiver is implicit.</p>
<p>This is one of those Ruby features that makes code pleasant to read, but it can also hide an important detail.</p>
<p>The receiver isn't missing.</p>
<p><strong>It is invisible.</strong></p>
<p>And that becomes interesting when we start asking when Ruby changes that context.</p>
<h2>There are scope gates for <code>self</code></h2>
<p>This is where I find it useful to stop thinking about every Ruby construct as if it creates a new <code>self</code>.</p>
<p>It doesn't.</p>
<p>A block is a good example.</p>
<p>Consider:</p>
<pre><code class="language-ruby">class Report
  def initialize(rows)
    @rows = rows
  end

  def failed_rows
    failures = []

    @rows.each do |row|
      next unless row[:status] == :failed

      failures &lt;&lt; {
        id: row[:id],
        reason: row[:error]
      }
    end

    failures
  end
end
</code></pre>
<p>Inside the block:</p>
<pre><code class="language-ruby">@rows.each do |row|
</code></pre>
<p><code>row</code> is the block's local value.</p>
<p>It is not <code>self</code>.</p>
<p>And the block does not automatically replace the surrounding <code>self</code>.</p>
<p>So inside that block, <code>self</code> is still the <code>Report</code> instance.</p>
<p>This gives us a useful mental distinction:</p>
<p><strong>Not every nested piece of Ruby code is a new</strong> <code>self</code> <strong>scope.</strong></p>
<p>A block can introduce local variables and control flow without automatically changing the receiver.</p>
<p>But structures such as:</p>
<pre><code class="language-ruby">class ...
module ...
def ...
</code></pre>
<p>create important boundaries in how Ruby evaluates code and what <code>self</code> refers to.</p>
<p>And then there are APIs that deliberately change it.</p>
<p>For this article, I'll call these boundaries <strong>scope gates</strong>. That's a mental model, not an official Ruby term.</p>
<p>The useful idea is simply:</p>
<blockquote>
<p><strong>A block is not automatically a</strong> <code>self</code> <strong>gate. Context-changing constructs and APIs are.</strong></p>
</blockquote>
<p>Once you see that, some Ruby behavior that initially feels inconsistent becomes much easier to predict.</p>
<p>And now we can look at the class side.</p>
<h2>The same keyword can point at the class</h2>
<p>Consider a factory-style class method:</p>
<pre><code class="language-ruby">class Invoice
  def initialize(customer, total)
    @customer = customer
    @total = total
  end

  def self.from_cents(customer, cents)
    new(customer, cents / 100.0)
  end

  def summary
    "#{@customer}: $#{format('%.2f', @total)}"
  end
end

invoice = Invoice.from_cents("Maya", 12500)

puts invoice.summary
</code></pre>
<p>This line:</p>
<pre><code class="language-ruby">def self.from_cents
</code></pre>
<p>can look like special Ruby grammar.</p>
<p>It isn't really a separate universe.</p>
<p>The important part is still the receiver.</p>
<p>While Ruby evaluates the body of the class definition, <code>self</code> refers to the <code>Invoice</code> class object.</p>
<p>So:</p>
<pre><code class="language-ruby">def self.from_cents
</code></pre>
<p>is essentially saying:</p>
<blockquote>
<p>Define <code>from_cents</code> on the object currently referenced by <code>self</code>.</p>
</blockquote>
<p>And in this context, that object is <code>Invoice</code>.</p>
<p>That is why this works:</p>
<pre><code class="language-ruby">Invoice.from_cents(...)
</code></pre>
<p>The class itself is an object, and that object can receive method calls.</p>
<p>Now compare the two situations:</p>
<pre><code class="language-ruby">invoice.summary
</code></pre>
<p>Here the receiver is an <code>Invoice</code> instance.</p>
<pre><code class="language-ruby">Invoice.from_cents(...)
</code></pre>
<p>Here the receiver is the <code>Invoice</code> class object.</p>
<p>Nothing about the keyword changed.</p>
<p><strong>The context did.</strong></p>
<p>That distinction is much more useful than memorizing "instance method versus class method" as two unrelated Ruby features.</p>
<h2>Rails makes this even more visible</h2>
<p>You see the same idea constantly in Rails models.</p>
<p>For example:</p>
<pre><code class="language-ruby">class Subscription &lt; ApplicationRecord
  scope :active, -&gt; {
    where(status: :active)
  }

  def self.for_customer(customer)
    active.where(customer: customer)
  end

  def cancel!
    update!(
      status: :cancelled,
      cancelled_at: Time.current
    )
  end
end
</code></pre>
<p>There are several receivers involved here.</p>
<p>When you call:</p>
<pre><code class="language-ruby">subscription.cancel!
</code></pre>
<p>the receiver is the <code>subscription</code> instance.</p>
<p>Inside <code>cancel!</code>, the call to:</p>
<pre><code class="language-ruby">update!(...)
</code></pre>
<p>is being sent to that instance.</p>
<p>But:</p>
<pre><code class="language-ruby">Subscription.for_customer(customer)
</code></pre>
<p>is sent to the <code>Subscription</code> class object.</p>
<p>And Rails adds another interesting layer with <code>scope</code>.</p>
<p>The block passed to <code>scope</code> is not simply "a new self." The surrounding Ruby context and the way Rails evaluates the scope both matter.</p>
<p>This is why a useful question when reading Rails code is not just:</p>
<blockquote>
<p>What method is this?</p>
</blockquote>
<p>but:</p>
<blockquote>
<p><strong>What object is receiving this method here?</strong></p>
</blockquote>
<p>That question scales much better when the code gets more dynamic.</p>
<h2>Then <code>instance_eval</code> deliberately moves the context</h2>
<p>Now we can make the context change explicit.</p>
<p>Consider a configuration object:</p>
<pre><code class="language-ruby">class Configuration
  def initialize
    @values = {}
  end

  def [](key)
    @values[key]
  end

  def values
    @values.dup
  end
end

config = Configuration.new

config.instance_eval do
  @values[:environment] = "production"
  @values[:region] = "eu-west"
  @values[:logging] = :verbose
end

puts config[:environment]
puts config[:region]
</code></pre>
<p>Why can this block access:</p>
<pre><code class="language-ruby">@values
</code></pre>
<p>directly?</p>
<p>Because <code>instance_eval</code> evaluates the block with the receiver as <code>self</code>.</p>
<p>Before entering the block, <code>self</code> referred to the surrounding context.</p>
<p>Inside:</p>
<pre><code class="language-ruby">config.instance_eval do
</code></pre>
<p><code>self</code> becomes <code>config</code>.</p>
<p>That is a deliberate context change.</p>
<p>And this is where the earlier idea of scope gates becomes useful.</p>
<p>The block itself didn't inherently create a new <code>self</code>.</p>
<p><code>instance_eval</code> did.</p>
<p>Ruby gives the programmer an explicit mechanism for saying:</p>
<blockquote>
<p>Evaluate this code as if this object is the current receiver.</p>
</blockquote>
<p>That is a very different thing from simply passing a block around.</p>
<h2><code>instance_exec</code> takes the same idea one step further</h2>
<p>There is a subtle difference between <code>instance_eval</code> and <code>instance_exec</code> that becomes important when designing DSLs.</p>
<p>Suppose we want to configure an object, but we also want to pass information into the block:</p>
<pre><code class="language-ruby">class Endpoint
  def initialize
    @settings = {}
  end

  def settings
    @settings
  end
end

endpoint = Endpoint.new

method = :post
path = "/users"

endpoint.instance_exec(method, path) do |http_method, route|
  @settings[:method] = http_method
  @settings[:path] = route
  @settings[:authenticated] = true
end

puts endpoint.settings
</code></pre>
<p>The important part is:</p>
<pre><code class="language-ruby">endpoint.instance_exec(method, path) do |http_method, route|
</code></pre>
<p><code>instance_exec</code> changes <code>self</code> to <code>endpoint</code>, just like the context-changing idea we saw with <code>instance_eval</code>.</p>
<p>But it also lets us pass arguments into the block.</p>
<p>So inside the block we have both:</p>
<pre><code class="language-ruby">self
</code></pre>
<p>pointing at <code>endpoint</code>, and:</p>
<pre><code class="language-ruby">http_method
route
</code></pre>
<p>coming from the outside.</p>
<p>That combination is useful when building expressive APIs.</p>
<p>It lets a DSL control the execution context without losing the ability to feed the block data.</p>
<p>And suddenly a pattern like:</p>
<pre><code class="language-ruby">resource :users do
  method :get
  path "/users"
end
</code></pre>
<p>starts looking less magical.</p>
<p>The DSL designer may be combining:</p>
<ul>
<li><p>a receiver that becomes <code>self</code></p>
</li>
<li><p>a block that defines the configuration</p>
</li>
<li><p>arguments or yielded values</p>
</li>
<li><p>method dispatch through that context</p>
</li>
</ul>
<p>The syntax is the surface.</p>
<p>The context is the machinery underneath.</p>
<h2>This is why Ruby DSLs can feel strange</h2>
<p>Once you start thinking in terms of context, Ruby DSLs become less mysterious.</p>
<p>You might see code that looks almost like configuration:</p>
<pre><code class="language-ruby">resource :users do
  path "/users"
  method :get
  authentication :required
end
</code></pre>
<p>The interesting question isn't only:</p>
<blockquote>
<p>What does <code>resource</code> do?</p>
</blockquote>
<p>It is also:</p>
<blockquote>
<p><strong>What is</strong> <code>self</code> <strong>while this block is being evaluated?</strong></p>
</blockquote>
<p>Maybe the DSL is yielding to a builder object.</p>
<p>Maybe it is using <code>instance_eval</code>.</p>
<p>Maybe it is using <code>instance_exec</code> because it needs both a changed receiver and arguments.</p>
<p>Maybe it is delegating method calls.</p>
<p>The surface syntax can look almost identical while the underlying execution model is very different.</p>
<p>That's why <code>self</code> becomes particularly useful when reading metaprogramming-heavy Ruby.</p>
<p>Instead of getting stuck on the syntax, look for the receiver.</p>
<p>Then look for the context.</p>
<p>Then look for the point where that context changes.</p>
<h2>So, who is <code>self</code>?</h2>
<p>I don't think of <code>self</code> as a definition I need to memorize anymore.</p>
<p>I think of it as a signpost.</p>
<p>When I see:</p>
<pre><code class="language-ruby">self.name = value
</code></pre>
<p>I ask:</p>
<blockquote>
<p>Which object is receiving this assignment?</p>
</blockquote>
<p>When I see:</p>
<pre><code class="language-ruby">def self.build
</code></pre>
<p>I ask:</p>
<blockquote>
<p>What is <code>self</code> while Ruby is evaluating this class body?</p>
</blockquote>
<p>When I see:</p>
<pre><code class="language-ruby">something.instance_eval do
</code></pre>
<p>I ask:</p>
<blockquote>
<p>Did Ruby just change the receiver for this block?</p>
</blockquote>
<p>When I see:</p>
<pre><code class="language-ruby">something.instance_exec(data) do |value|
</code></pre>
<p>I ask two questions:</p>
<blockquote>
<p>What is <code>self</code> now?</p>
</blockquote>
<p>and:</p>
<blockquote>
<p>What data was passed into this context?</p>
</blockquote>
<p>And when I see a Ruby DSL that seems to have methods appearing out of nowhere, I ask:</p>
<blockquote>
<p><strong>Who is</strong> <code>self</code> <strong>here, and where did that context come from?</strong></p>
</blockquote>
<p>That question usually gets me closer to the actual behavior than simply remembering what the keyword means.</p>
<p>Because <code>self</code> isn't really the interesting part.</p>
<p><strong>Context is.</strong></p>
<p>Once you start reading Ruby through that lens, <code>self</code> becomes less of a keyword to memorize and more of a way to locate yourself inside Ruby's object model.</p>
<p>And I'm curious how other Ruby developers approach this.</p>
<p>Do you consciously think about <code>self</code> while reading Ruby code, or has it become one of those things you only notice when the context suddenly changes?</p>
]]></content:encoded></item></channel></rss>