<?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" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Colin Kelley on Medium]]></title>
        <description><![CDATA[Stories by Colin Kelley on Medium]]></description>
        <link>https://medium.com/@colindkelley?source=rss-60afd1b90f89------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*kix5KsPTiRA7VF0H</url>
            <title>Stories by Colin Kelley on Medium</title>
            <link>https://medium.com/@colindkelley?source=rss-60afd1b90f89------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Mon, 16 Nov 2026 19:34:35 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@colindkelley/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Should I use Struct for Value Objects in Ruby?]]></title>
            <link>https://engineering.invoca.com/should-i-use-struct-for-value-objects-in-ruby-9e3eec9d1c62?source=rss-60afd1b90f89------2</link>
            <guid isPermaLink="false">https://medium.com/p/9e3eec9d1c62</guid>
            <category><![CDATA[struct]]></category>
            <category><![CDATA[value-objects]]></category>
            <category><![CDATA[ruby]]></category>
            <dc:creator><![CDATA[Colin Kelley]]></dc:creator>
            <pubDate>Mon, 23 Aug 2021 17:47:13 GMT</pubDate>
            <atom:updated>2021-08-23T18:46:49.765Z</atom:updated>
            <content:encoded><![CDATA[<p>The Ruby standard library includes a clever class factory called<a href="https://ruby-doc.org/core-2.7.0/Struct.html">Struct</a>. What is a “class factory”? It’s a design pattern where code generates a Class for you. In the case of Struct, you pass it a list of attributes whose values you would like stored, and it returns a Value Class built for storing <a href="https://en.wikipedia.org/wiki/Value_object">Value Objects</a>.</p><p>Here’s an example:</p><pre>irb&gt; require &lt;struct&gt;</pre><pre>irb&gt; FullName = Struct.new(:first_name, :last_name);<br>irb&gt; fn = FullName.new(&#39;Colin&#39;, &#39;Kelley&#39;)<br>=&gt; #&lt;struct FullName first_name=&quot;Colin&quot;, last_name=&quot;Kelley&quot;&gt;<br>irb&gt; fn.last_name<br>=&gt; &quot;Kelley&quot;</pre><p>The Struct.new line above is equivalent to</p><pre>class FullName<br>  attr_accessor :first_name, :last_name</pre><pre>  def initialize(first_name = nil, last_name = nil)<br>    @first_name = first_name<br>    @last_name = last_name<br>  end<br>end</pre><h3>What are the Pros and Cons?</h3><p>I only see one “Pro” of Struct: succinctness. You get those 5 lines of code (not counting ends) written for you.</p><p>But here are some “Cons”:</p><ol><li>Notice those are attr_accessors, so every Struct is mutable. In modern programming we know to avoid mutability whenever possible. And here it certainly is possible! As always with Value Classes: if you want different values, just make a new object. By definition, <a href="https://en.wikipedia.org/wiki/Value_object">Value Objects</a> are fungible; they have no identity of their own.</li><li>Notice those = nil default values on every field passed to initialize?That is not good practice to have methods fill in default values just because they can. We’d only want defaults for attributes that are optional. (For example, if we added amiddle_name attribute.) And defaulting tonil is often worst practice; in our experience, dereferencing nil is the most common bug in Ruby! Suppose we added thatmiddle_name attribute, and wanted to make it optional. We might choose empty string as its default rather than nil.</li><li>If you have more than a couple fields, it might be a good choice for initialize to use keyword arguments, at least for the optional attributes like middle_name. ButStruct doesn’t support that. The arguments are always positional.</li></ol><p>Given these cons, I recommend not using Struct.</p><h3>What‘s the Best Alternative to Struct?</h3><p>Instead of usingStruct, just write out your Value Class. It’s easy:</p><pre>class FullName<br>  attr_reader :first_name, :last_name</pre><pre>  def initialize(first_name, last_name)<br>    @first_name = first_name.to_s<br>    @last_name = last_name.to_s<br>  end<br>end</pre><p>Notice the improvements we were able to make over what Struct would have written for us:</p><ol><li>The attr_readers allow read access but do not allow mutation.</li><li>The initialize method doesn’t have any defaults. Callers need to pass in both attributes.</li><li>The initialize method normalizes the attributes by calling to_s on them when storing them. So if, for example, a nil value were passed in, it would get normalized to an empty string here.</li></ol><p>And now, with a first-class Class, we&#39;re in a great position to add methods when helpful. For example, since our attributes are all strings, it would be helpful for our class to conform to Ruby’sto_s convention, so that any FullName value can be converted to a combined string:</p><pre>def to_s<br>  [first_name, last_name].join(&#39; &#39;)<br>end</pre><p>Note that the above method stayed simple because it could count on first_name and last_name beingStrings . (join will raise an exception if any of the array elements are not Strings.)</p><h3>In Conclusion</h3><p>Go forth and write clean and simple Value Classes in your Ruby code. But write them out so you can follow best practices. Don’t letStruct lead you astray!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=9e3eec9d1c62" width="1" height="1" alt=""><hr><p><a href="https://engineering.invoca.com/should-i-use-struct-for-value-objects-in-ruby-9e3eec9d1c62">Should I use Struct for Value Objects in Ruby?</a> was originally published in <a href="https://engineering.invoca.com/">Invoca Engineering Blog</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Ruby Constants with Rails]]></title>
            <link>https://engineering.invoca.com/ruby-constants-with-rails-and-how-to-avoid-the-already-initialized-constant-x-warning-753d28f17691?source=rss-60afd1b90f89------2</link>
            <guid isPermaLink="false">https://medium.com/p/753d28f17691</guid>
            <category><![CDATA[ruby]]></category>
            <category><![CDATA[rails]]></category>
            <category><![CDATA[software-development]]></category>
            <dc:creator><![CDATA[Colin Kelley]]></dc:creator>
            <pubDate>Thu, 11 Oct 2018 14:01:03 GMT</pubDate>
            <atom:updated>2018-10-11T19:58:07.363Z</atom:updated>
            <content:encoded><![CDATA[<h3>Ruby Constants with Rails (and How to Avoid the “already initialized constant X” Warning)</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*xAFAiAxqZVrOVLBTo9tf6w.jpeg" /></figure><p>If you have worked in Rails code (or just plain Ruby code) long enough, you have no doubt seen many messages similar to a.rb:10: warning: already initialized constant A::MAX. What causes them? How can you debug them? What are the best practices for using constants so you avoid them in the future? Read on!</p><h3>Behavior in Plain Ruby</h3><p>Ruby has “open classes”, meaning they can be extended beyond the initial declaration. Methods may be redefined without any errors or warnings.</p><p>However, Ruby is not tolerant of reparsing the same class definition if it has constants declared in it. When those constants are re-initialized, they will generate the warning already initialized constant X, as shown below:</p><pre>$ cat a.rb<br>class A<br>  MAX = 10<br>end</pre><pre>$ cat load_a.rb<br>load &#39;./a.rb&#39;<br>load &#39;./a.rb&#39;</pre><pre>$ ruby load_a.rb<br>a.rb:2: warning: already initialized constant A::MAX<br>a.rb:2: warning: previous definition of MAX was here</pre><h4>require Idempotence</h4><p>Unlike load, require is idempotent in Ruby. It returns false and does nothing on subsequent invocations:</p><pre>$ cat require_a.rb<br>result0 = require &#39;./a.rb&#39;<br>result1 = require &#39;./a.rb&#39;<br>puts [result0, result1]</pre><pre>$ ruby require_a.rb<br>true<br>false</pre><h4>require_relative Is Just a Wrapper</h4><p>Ruby’s require_relative is just a wrapper around require, so everything said about require applies to require_relative. The idempotence detector is shared across them in fact, so the above example works the same even if the second require &#39;./a.rb&#39; were written as require_relative &#39;a.rb&#39;.</p><h4>Filename Aliasing</h4><p>It is possible to trick the Ruby require idempotence detector by using what appear to be different paths to the same file.</p><p><strong>‘./’ and ‘../’<br></strong>Ruby normalizes file paths by collapsing &#39;./&#39; and &#39;../&#39;, so using either of these will not trip it up.</p><p><strong>Case Sensitivity in Filenames</strong><br>Ruby assumes case-sensitive paths, so you will defeat the require idempotence if you mix different path casing to the same file.</p><p><strong>Linked Files or Paths</strong><br>Ruby does not know about links in the file system, so you will defeat the require idempotence if you mix different linked paths to the same file.</p><h4>Avoid Constant Coupling</h4><p>Constants are evaluated at class parse time, so you should be careful to avoid creating coupling, as in this example:</p><pre>class AbcController<br>  MAX_ITEMS = Widget::MAX + 1<br>  CLIENT_ID = Secrets[&#39;Abc&#39;][&#39;client_id&#39;]</pre><pre>  ...<br>end</pre><p>The MAX_ITEMS initialization above will force coupling to Widget immediately right when Controller is being parsed. To avoid this but still keep the code DRY, consider making a shared constant in a namespace that can be included by multiple consumers.</p><p>The CLIENT_ID initialization above means that the Secrets code has to run right then, at class parse time. This usually is not appropriate; if code has to run, it probably doesn&#39;t pass the test to be a constant! Better in that case to make it a class method, perhaps with memoization if there is no need to support the value changing over the lifetime of the process:</p><pre>class AbcController<br>  class &lt;&lt; self<br>    def client_id<br>      @client_id ||= Secrets[&#39;Abc&#39;][&#39;client_id&#39;]<br>    end<br>  end<br>  ...<br>end</pre><h4>Freeze Mutable Constants</h4><p>It seems counter-intuitive…but constants in Ruby may be mutated! For example, consider a constant hash:</p><pre>class AbcController<br>  DEFAULT_ARGS = { storage_engine: :AWS_S3 }<br>  ...<br>end</pre><p>And then this code that passes that option to a method:</p><pre>download_file(bucket, AbcController::DEFAULT_ARGS)</pre><p>which eventually winds up mutating the argument:</p><pre>def download_file(bucket, options = {})<br>  ...<br>  storage_engine = options.delete(:storage_engine)<br>end</pre><p>When that code runs, AbcController::DEFAULT_ARGS will be changed for the entire process!</p><p>To prevent this mistake, always freeze mutable constants:</p><pre>class AbcController<br>  DEFAULT_ARGS = { storage_engine: :AWS_S3 }<strong>.freeze</strong><br>  ...<br>end</pre><p>Note: Assuming you have # frozen_string_literal: true at the top of the file, strings literals are not mutable. So there’s no need to put .freeze after string constants. In fact, the ever-vigilant Rubocop will cite you if you do.</p><h3>Behavior in Rails</h3><p>Things get more complicated in Rails.</p><h4>Rails Auto-Loader</h4><p>Rails has an auto-loader that knows how to load models and controllers and libs automatically when their name is mentioned. Also the auto-loader knows how to reload in development mode. It goes to great effort to avoid the “already initialized constant X” warning during this process.</p><p><strong>You should never </strong><strong>require a file which is auto-loadable by Rails.</strong> Doing so will wind up loading the file twice… making this the most likely cause of “already initialized constant X” warning. By default Rails is configured to autoload from any sub-folders ofapp/ Your project may be configured to auto-load other folders likelib/since that was in the default auto-load list for early versions of Rails.</p><h4>Rails Non-Idempotence</h4><p>Beware that some class macros are not idempotent in Rails, so breaking the above rule can cause bugs. One example is alias_method_chain ... but that is deprecated now, in favor of Module#prepend. Another example is validations. If the file is parsed twice, the validations will be declared twice! For example:</p><pre>pry&gt; u = User.first;<br>pry&gt; u.first_name = &#39;&#39;;<br>pry&gt; u.valid?<br>false<br>pry&gt; u.errors.full_messages<br>[&quot;First name can&#39;t be blank&quot;]<br><br>pry&gt; require &#39;./app/models/user.rb&#39;  # &lt;--- never do this!<br>true<br>pry&gt; u.valid?<br>false<br>pry&gt; u.errors.full_messages<br>[&quot;First name can&#39;t be blank&quot;, &quot;First name can&#39;t be blank&quot;]  # Uh oh!</pre><h3>Technique for Tracking Down Repeated Loading</h3><p>If you are seeing the already initialized constant X warning, you can track down how that file got loaded by adding code like this to the file in question, to show the call stack when it&#39;s loaded:</p><pre># frozen_string_literal: true<br><strong>puts &quot;Start loading AbcController&quot;, caller, &quot;&quot;</strong></pre><pre>class AbcController<br>  ...<br>end</pre><pre><strong>puts &quot;Finish loading AbcController&quot;</strong></pre><p>Or, you may need to write to a log rather than using puts. By having the caller logged, you will be able to tell what code paths are responsible for loading the file each time.</p><h3>Conclusion</h3><p>Constants are a powerful tool in Ruby. They help keep code DRY and can make it easier to understand and debug, by separating static concerns that cannot change during process run-time from those that can. Hopefully this article will help you use Ruby constants more effectively.</p><p>We’re always looking for amazing people to join our team. Check out our <a href="https://www.invoca.com/company/careers">job listings</a>.</p><p>If this was interesting and helpful to you, please help share this with others by clapping 👏.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=753d28f17691" width="1" height="1" alt=""><hr><p><a href="https://engineering.invoca.com/ruby-constants-with-rails-and-how-to-avoid-the-already-initialized-constant-x-warning-753d28f17691">Ruby Constants with Rails</a> was originally published in <a href="https://engineering.invoca.com/">Invoca Engineering Blog</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>