<?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 Carlos Martinez on Medium]]></title>
        <description><![CDATA[Stories by Carlos Martinez on Medium]]></description>
        <link>https://medium.com/@carlos_42328?source=rss-434ff3d353c------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*tVNOraua-H2JC_QR3090oA.png</url>
            <title>Stories by Carlos Martinez on Medium</title>
            <link>https://medium.com/@carlos_42328?source=rss-434ff3d353c------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Tue, 24 Nov 2026 11:23:52 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@carlos_42328/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[Effective Ruby Idioms to Write Better Code]]></title>
            <link>https://medium.com/@carlos_42328/effective-ruby-idioms-to-write-better-code-eef5fbc5788b?source=rss-434ff3d353c------2</link>
            <guid isPermaLink="false">https://medium.com/p/eef5fbc5788b</guid>
            <category><![CDATA[ruby]]></category>
            <dc:creator><![CDATA[Carlos Martinez]]></dc:creator>
            <pubDate>Thu, 10 Jan 2019 22:02:06 GMT</pubDate>
            <atom:updated>2019-01-10T22:02:06.732Z</atom:updated>
            <content:encoded><![CDATA[<p>Ruby is a very elegant language, its idioms can make your code incredibly expressive and help you create easy to read and maintainable code. However, it’s not the simplest language to master, and things can go wrong if you don’t pay attention to best practices.</p><p>The intention of this series of posts is to summarize some useful points from <a href="https://www.amazon.com.mx/Effective-Ruby-Specific-Write-Better/dp/0133846970/ref=sr_1_1?ie=UTF8&amp;qid=1547074871&amp;sr=8-1&amp;keywords=effective+ruby">Effective Ruby: 48 Specific Ways to Write Better Ruby</a>, that you can start using to improve your code, so I’ll get to it right away!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/640/0*j2t6Us6OyS9IXdJF.gif" /></figure><h3>UNDERSTAND WHAT RUBY CONSIDERS TO BE TRUE</h3><p>Every language has its own way of dealing with Boolean values, in some of them, the number zero is considered to be a <em>false</em> value, while all other numbers are <em>true</em>. Empty strings, arrays, and objects can also have different truthiness across different languages, so understanding how this works in Ruby can help discover bugs quickly.</p><p>In Ruby, the rule for truthiness is very simple, so it’s worth memorizing it:</p><blockquote>Every value is true except false and nil</blockquote><p>Consider the following:</p><pre>irb&gt; !![]<br>=&gt; true</pre><pre>irb&gt; !!false<br>=&gt; false</pre><pre>irb&gt; !!nil<br>=&gt; false</pre><pre>irb&gt; !!{}<br>=&gt; true</pre><pre>irb&gt; !!0<br>=&gt; true</pre><p>Understanding this will make it easier to know whether an expression will evaluate to <em>true</em> or <em>false. </em>Sometimes, however, you want to differentiate between <em>false</em> and <em>nil</em>. In certain contexts, <em>false</em> can mean that something is disabled, while <em>nil</em> can mean that something wasn’t explicitly specified. The easiest way to achieve this is to use the nil? method.</p><h3>TREAT ALL OBJECTS AS IF THEY COULD BE NIL</h3><pre>undefined method `fubar&#39; for nil:NilClass (NoMethodError)</pre><p>This error is a like plague even in well tested applications, it happens when you call a method on an object and it turns out to be that pesky <em>nil</em> object, the one and only object from the <em>NilClass</em> class (remember, that in Ruby, everything is an object, even true, false or classes!). There’s a large number of ways that <em>nil</em> can unexpectedly get introduced into your application. The best defense is to assume that any object might actually be the <em>nil</em> object. This includes arguments passed to methods and return values from them.</p><p>One of the easiest ways to avoid invoking methods on the <em>nil</em> object is by using the <em>nil?</em> method. It returns true if the receiver (the object where you’re calling the method) is <em>nil</em> and <em>false</em> otherwise. For example:</p><pre>irb&gt; nil.nil?<br>=&gt; true</pre><pre>irb&gt; false.nil?<br>=&gt; false</pre><pre>irb&gt; hash = {}<br>irb&gt; hash[:test].nil?<br>=&gt; true</pre><p>It’s often easier to explicitly convert a variable to the expected type rather than worry about <em>nil</em> all the time, the <em>Object</em> class defines several conversion methods which can come in handy in this case. For example:</p><pre>irb&gt; 42.to_s<br>=&gt; &quot;13&quot;</pre><pre>irb&gt; nil.to_s<br>=&gt; &quot;&quot;</pre><p>As you can see, NilClass#to_s returns an empty string. What makes this really nice is that String#to_s simply returns self without performing any conversion or copying. If a variable is already a string, then using .to_s will have minimal overhead. This allows you to safely work with an argument that might be <em>nil:</em></p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/96a0041dc4fa0006b1211b29b9ddb2b4/href">https://medium.com/media/96a0041dc4fa0006b1211b29b9ddb2b4/href</a></iframe><p>Almost all the built-in classes have matching conversion methods: .to_a, .to_i and .to_f are some examples.</p><h3>BE AWARE OF THE DIFFERENT BEHAVIORS OF SUPER</h3><p>Even though super is used and acts like a method, it’s actually a language keyword. This difference is important because super changes its behavior based on something that is supposed to be optional in Ruby, parentheses. Choosing to omit parentheses when using super changes the way it works. To see how parentheses change things let’s review the three ways that super can be written:</p><ul><li>If you givesuper at least one argument then it acts like a regular Ruby method and the parentheses are optional. In this form, super passes along the exact arguments it was given to the target method.</li><li>If no arguments are given <em>and</em> no parentheses are used thensuper will invoke the target method with <em>all</em> of the arguments which were given to the enclosing method. It also forwards along the method’s block if one is associated with it.</li><li>When you don’t actually want to pass any arguments to the overridden method you need to write super with an empty set of parentheses, i.e. super(). This looks especially weird in Ruby. This use ofsuper seems unnatural but it’s the only way to call an overridden method with no arguments (and no block).</li></ul><p>Here are the same rules from above expressed in code:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/a7b26d04fd6499f152d86a0bb2fed3a1/href">https://medium.com/media/a7b26d04fd6499f152d86a0bb2fed3a1/href</a></iframe><h3>Prefer Struct to Hashes for Structured Data</h3><p>Hash tables are useful, general-purpose data structures which are employed heavily by Ruby programmers. When it comes to working with key-value pairs, Hash is definitely the go to class.</p><p>However, when working with structured data in an OOP language we often have better choices than hashes.</p><p>Say you’re interested in exploring annual weather data from a local weather station. Armed with a CSV file you plan to load the data into an array and play around with it. Each row in the CSV file contains temperature statistics for a single month. You’ve decided to extract the interesting columns from each row and store them in a Hash. Consider this:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/811d26a5d7ee02d92b6f4cf48cc80581/href">https://medium.com/media/811d26a5d7ee02d92b6f4cf48cc80581/href</a></iframe><p>Each month in the @readings array has high and low temperatures. You’d like to know the mean temperature of the year which means you’ll also need to know the mean temperature for each month. However, we resort to adding this logic into the more general aggregation method mean.</p><p>This array of hashes represents a collection of objects, except that you can’t access their attributes through getter methods. You have to use the hash index operator instead. This might be a minor issue but it’s one which will have an impact on the AnnualWeather class’ interface. Furthermore, every time you want to work with these hashes internally you will need to go back to the initializemethod to remind yourself which keys are available. Again, as long as the keys are set in a single method the burden is fairly low.</p><p>Using hashes to stand in for really simple classes happens a lot in Ruby. Sometimes it’s completely fine but more often than not we really should be creating dedicated types for these sort of objects. The thought of creating a new class for something so simple seems like an unnecessary chore. Fortunately, that’s exactly what the Struct class is for.</p><p>Here’s how our class would look like if we used a Struct object instead:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/9312237084697e623bcd23519e8498a0/href">https://medium.com/media/9312237084697e623bcd23519e8498a0/href</a></iframe><p>The existing mean method required few changes but now has a much better OOP feel to it. Accessing the high and low attributes through getter methods has a subtle side effect too. Typos in attribute names will now raise a NoMethodError exception. The same isn’t the case when using hashes. Attempting to access an invalid key in a hash doesn’t raise an exception but instead returns nil. This usually means that you’ll wind up with a more obscure TypeError exception later in the code.</p><p>Another improvement with Struct is that we can now do something which we wanted to do earlier, define a mean method for each month. We can optionally pass a block to Struct::new. For example, we can modify our Struct definition to include the mean method:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/a8480b778f1ac17b69e1dbb74a20c5f7/href">https://medium.com/media/a8480b778f1ac17b69e1dbb74a20c5f7/href</a></iframe><p>For those times when it seems too heavy-handed to create a new class, Struct can be very useful. And unlike a bunch of unrelated yet uniform hashes, Struct lets you define instance and class methods. That’s perfect for when you need to add a few simple behaviors to these otherwise boring objects.</p><h3>DUPLICATE COLLECTIONS PASSED AS ARGUMENTS BEFORE MUTATING THEM</h3><p>Most objects are passed around as references and not as actual values. When these types of objects are inserted into a container the collection class is actually storing a reference to the object and not the object itself.</p><p>Mutating an element of an array affects the original object which may still be available outside of the array. Similarly, when a method alters one of its arguments, those changes are visible outside of the method. Sometimes that’s the entire point of the method and its author was kind enough to suffix the method name with “!”. Most of the time, however, you really don’t want your objects to be mutated behind your back.</p><p>Collections (such as arrays and hashes) tend to be modified heavily during their lifetime. A common mistake is to mutate a collection which was passed as an argument to a method. Often without realizing that the original collection will also be modified.</p><p>Consider the following:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/90a13740b59ce34af0b3b17bd03e7c77/href">https://medium.com/media/90a13740b59ce34af0b3b17bd03e7c77/href</a></iframe><p>As you can see, the numbers array was modified after it was mutated within the OddPunisher class. The delete_if method mutates the collection instead of returning a new copy. If someone using this class expected the numbers array to remain unchanged, they would definitely have a surprise.</p><p>One way of fixing this is by using a method that doesn’t mutate the collection (using reject instead of delete_if). However, there are times where you do need to mutate the collection, and for those cases what you want is to create a copy of the collection instead of a reference to the original. This way you can mutate the new collection however you want.</p><p>There are two methods in Ruby which allow you to create copies of objects, dup and clone. They’re not equivalent, but you usually want to use dup when you’re planning to mutate the resulting object. Our class then simply needs to be modified like this:</p><pre>@numbers = numbers.dup</pre><blockquote>It’s a common pattern to duplicate collection objects given as method arguments.</blockquote><p>One thing to be aware of though is that dup and clone return shallow copies, for collection classes this means that the container is duplicated but not the elements. Consider this:</p><pre>irb&gt; a = [&quot;Polar&quot;]<br> <br>irb&gt; b = a.dup &lt;&lt; &quot;Bear&quot;<br>#&gt; [&quot;Polar&quot;, &quot;Bear&quot;]<br> <br>irb&gt; b.each {|x| x.sub!(&#39;lar&#39;, &#39;oh&#39;)}<br>#&gt; [&quot;Pooh&quot;, &quot;Bear&quot;]<br> <br>irb&gt; a<br>#&gt; [&quot;Pooh&quot;]</pre><p>In case you need to create a deep copy of a collection you can override theinitialize_copy method if you’re creating a new collection class, this will allow you to control the depth of the duplication process. If you’re using existing collections then you’ll have to roll your own, there’s a quick solution which works the majority of the time:</p><pre>irb&gt; a = [&quot;Monkey&quot;, &quot;Brains&quot;]<br> <br>irb&gt; b = Marshal.load(Marshal.dump(a))<br> <br>irb&gt; b.each(&amp;:upcase!); b.first<br>#&gt; &quot;MONKEY&quot;<br> <br>irb&gt; a.last<br>#&gt; &quot;Brains&quot;</pre><p>This comes with a lot of limitations, it takes time to serialize and deserialize an object, and you need to consider the amount of memory needed. This method will also not work with some of the core Ruby classes, these include the <em>IO</em> and <em>File</em> classes. Moreover, classes which contain closures or classes with singleton methods cannot be serialized.</p><h4>Things to Remember</h4><ul><li>Every value is true <em>except</em> false and nil.</li><li>Unlike in a lot of languages, the number zero is true in Ruby.</li><li>If you need to differentiate between false and nil, either use the nil? method or use the “==” operator with false as the left operand.</li><li>Due to the way Ruby’s type system works, any object can be nil.</li><li>The nil? method returns true if its receiver is nil and false otherwise.</li><li>Using super with no arguments and no parentheses is equivalent to passing it all of the arguments which were given to the enclosing method.</li><li>If you want to use super without passing the overridden method any arguments, you must use empty parentheses, i.e. super().</li><li>When dealing with structured data which doesn’t quite justify a new class prefer using Struct toHash.</li><li>Assign the return value of Struct::new to a constant and treat that constant like a class.</li><li>Method arguments in Ruby are passed as references, not values. Notable exceptions to this rule are Fixnum objects.</li><li>Duplicate collections passed as arguments before mutating them.</li><li>The dup and clone methods only create shallow copies.</li></ul><p>All credits to the author of <a href="https://www.amazon.com.mx/Effective-Ruby-Specific-Write-Better/dp/0133846970/ref=sr_1_1?ie=UTF8&amp;qid=1547074871&amp;sr=8-1&amp;keywords=effective+ruby">Effective Ruby: 48 Specific Ways to Write Better Ruby</a>, I definitely recommend the book for anyone who’s trying to improve his Ruby code, there’s much more useful information available in the book than what is presented here.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=eef5fbc5788b" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Mocking API responses with React Apollo]]></title>
            <link>https://medium.com/@carlos_42328/mocking-api-responses-with-react-apollo-11eb4610debe?source=rss-434ff3d353c------2</link>
            <guid isPermaLink="false">https://medium.com/p/11eb4610debe</guid>
            <category><![CDATA[react]]></category>
            <category><![CDATA[apollo-client]]></category>
            <category><![CDATA[graphql]]></category>
            <category><![CDATA[software-testing]]></category>
            <dc:creator><![CDATA[Carlos Martinez]]></dc:creator>
            <pubDate>Sat, 19 Aug 2017 22:49:59 GMT</pubDate>
            <atom:updated>2017-08-19T22:49:59.452Z</atom:updated>
            <content:encoded><![CDATA[<p>Apollo Client and the GraphQL tools that have been made open source within the last years are pretty awesome, the community that is being builded around them is great. However, as with every new technology, there are a lot of things that need to mature and improve.</p><p>Documentation on testing is definitely one of the bits that needs a lot of improvements, it isn’t clear what to do, and I personally found myself digging into the source code to understand what to do.</p><p>One of the problems I faced was that I wanted to use mock responses when testing my app components, and there are at least two ways of doing this:</p><p>The first way is to use <a href="https://github.com/apollographql/graphql-tools">graphql-tools</a>. From their docs:</p><blockquote>This package allows you to use the GraphQL schema language to build your <a href="https://github.com/graphql/graphql-js">GraphQL.js</a> schema, and also includes useful schema tools like per-type mocking.</blockquote><p>You can use this library together with a custom MockNetworkInterface to return mocked responses to your components:</p><pre>const { mockServer } = require(&quot;graphql-tools&quot;);<br>const { print } = require(&quot;graphql/language/printer&quot;);<br><br>class MockNetworkInterface {<br>  constructor(schema, mocks = {}) {<br>    if (!schema) {<br>      throw new Error(&#39;Cannot create Mock Api without specifying a schema&#39;);<br>    }<br>    this.mockServer = mockServer(schema, mocks);<br>  }<br><br>  query(request) {<br>    return this.mockServer.query(print(request.query), request.variables);<br>  }<br>}</pre><p>This is nice, and very flexible, with graphql-tools you can do pretty much whatever you do in your actual API.</p><p>What I didn’t like about this approach is that you need your schema in sync with the schema defined in your API (you can do this <a href="https://github.com/Carlows/localbitcoins-relay/blob/master/scripts/getSchema.js">making an instrospection query to your backend</a>), I also found this approach overcomplicates things unnecessarily.</p><p>The second (and simpler) approach I found was to use the mockNetworkInterface class, this class is defined in react-apollo/test-utils, you can have a <a href="https://github.com/apollographql/react-apollo/blob/master/src/test-utils.tsx#L16">peek on it here</a>.</p><p>To use it, you first need to define some Mock Requests (these requests need to be exactly the same your components will make):</p><pre>const GraphQLMocks = [<br>  {<br>    request: {<br>      query: UserProfileQuery,<br>      variables: {}<br>    },<br>    result: {<br>      data: {<br>        current_user: {<br>          id: 1,<br>          first_name: &#39;Foo&#39;,<br>          last_name: &#39;Bar&#39;,<br>          email: &#39;<a href="/service/mailto:foo@example.com">foo@example.com</a>&#39;<br>        }<br>      }<br>    }<br>  }<br>];</pre><p>The UserProfileQuery is exported from your component:</p><pre>export const UserProfileQuery = gql`<br>  query userProfile {<br>    current_user {<br>      id<br>      first_name<br>      last_name<br>      email<br>    }<br>  }<br>`;</pre><p>And this is how you use it to setup your tests:</p><pre>import { mockNetworkInterface } from &#39;react-apollo/test-utils&#39;;<br>import ApolloClient from &#39;apollo-client&#39;;<br>import { ApolloProvider } from &#39;react-apollo&#39;;<br>import { mount } from &#39;enzyme&#39;;<br>import App from &#39;../App.js&#39;;<br>import React from &#39;react&#39;;<br><br>const setupTests = () =&gt; {<br>  const networkInterface = mockNetworkInterface(...mocks);<br>  // or mockNetworkInterface.apply(null, mocks);<br>  const client = new ApolloClient({ <br>    networkInterface, <br>    addTypename: false <br>  });<br><br>  const wrapper = mount(<br>    &lt;ApolloProvider client={client}&gt;<br>      &lt;App /&gt;<br>    &lt;/ApolloProvider&gt;<br>  );<br><br>  return {<br>    wrapper<br>  };<br>};</pre><p>It is important that you pass addTypename: false to ApolloClient, otherwise you would have to include a __typename field in all your mocks and queries.</p><p>Now any queries your components make will be handled by your mocked responses, you have full control of what you want to return.</p><p>And that’s it! I really hope this gets documented in the future and I’ll be looking forward to make mocking and testing easier with React Apollo.</p><p>You can see a full example <a href="https://github.com/Carlows/alt-market/blob/master/src/__tests__/feed.js">here</a>, the test setup if being created in <a href="https://github.com/Carlows/alt-market/blob/master/src/common/testHelpers.js">this file</a>.</p><p>I’ll gladly appreciate any comments and suggestions!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=11eb4610debe" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>