<?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 Michael Pearson on Medium]]></title>
        <description><![CDATA[Stories by Michael Pearson on Medium]]></description>
        <link>https://medium.com/@mipearson?source=rss-b55649fdb439------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*IA0bVIlbdq2dqT_1na9-5g.jpeg</url>
            <title>Stories by Michael Pearson on Medium</title>
            <link>https://medium.com/@mipearson?source=rss-b55649fdb439------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Wed, 02 Dec 2026 00:37:44 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@mipearson/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[Image serving with Content Addressable Storage, S3, and ImgIx]]></title>
            <link>https://medium.com/@mipearson/image-serving-with-content-addressable-storage-s3-and-imgix-6770a181879f?source=rss-b55649fdb439------2</link>
            <guid isPermaLink="false">https://medium.com/p/6770a181879f</guid>
            <category><![CDATA[rails]]></category>
            <category><![CDATA[image-processing]]></category>
            <category><![CDATA[aws]]></category>
            <dc:creator><![CDATA[Michael Pearson]]></dc:creator>
            <pubDate>Thu, 05 Jul 2018 06:23:32 GMT</pubDate>
            <atom:updated>2018-07-05T06:23:32.949Z</atom:updated>
            <content:encoded><![CDATA[<p>Marketplacer and its websites served user-provided web-optimised images from the same webserver as its actual application, and stored both the original image and the web-optimised versions on disk. Each image’s filename was stored in a column on the related model, and uploads were handled with the Ruby gem carrierwave.</p><p>Marketplacer’s websites would often have many duplicate images stored against database records and on disk:</p><ul><li>a templating system allowed users to copy manufacturer provided images to their own adverts</li><li>users would duplicate existing records between stores of the same franchise</li><li>different sites with the same models would use the same original images</li></ul><p>These duplicate images, along with handling the web-optimisation of the images and storage server-side, presented problems:</p><ul><li>storing images on disk made it difficult for us to horizontally scale without using shared filesystems</li><li>developers &amp; test environments using production data would refer to images and assets that did not exist on the local environment</li><li>copying images from templates or between users could take time and use additional disk space</li><li>changing our web-optimisation method (eg, image size, compression ratio) required us to re-process every single uploaded image</li></ul><p>To correct these problems we decided to rebuild our image processing &amp; serving architecture based on ImgIx, S3 and a concept called “Content Addressable Storage”.</p><p>ImgIx allowed us to optimise our images for the web on the fly by specifying the desired resolution, compression and image format in the URL provided to the user. For added security, we opted to sign these URLs so that a user could not retrieve the original asset by modifying the URL.</p><p>We created a single S3 bucket for ImgIx to use to source the image originals. This S3 bucket would be used by marketplacer websites, across development, test, staging and production, and for all asset types. We were able to do this without risk of corrupting production assets due to the nature of Content Addressable Storage.</p><p>Content Addressable Storage meant that every image’s location in S3 is representative of its contents. Two files with different contents will aways have a different path &amp; filename, and two files with the same contents will always have the same path &amp; filename.</p><p>Here’s how it works:</p><ul><li>a user uploads an image to a web application</li><li>the image is stored in a temporary directory</li><li>we create SHA digest of its content (eg CgqfKmdylCVXq1NV12r0Qvj2XgE)</li><li>we infer the image’s location is S3 based on that digest (Cg/qfKmdylCVXq1NV12r0Qvj2XgE)</li><li>we check S3 to determine whether we already have an image in this location</li><li>if we don’t, we upload the image to the location</li><li>we store the image’s location in the database on the relevant database record</li><li>we later serve a link to a processed version of that image via ImgIx (eg <a href="https://marketplacer.imgix.net/Cg/qfKmdylCVXq1NV12r0Qvj2XgE?auto=format&amp;fm=pjpg&amp;fit=max&amp;w=1600)">https://marketplacer.imgix.net/Cg/qfKmdylCVXq1NV12r0Qvj2XgE?auto=format&amp;fm=pjpg&amp;fit=max&amp;w=1600)</a></li></ul><p>During the first month of rolling this mechanism out to production, we had a 5% hit rate of duplicate images on all uploads.</p><p>We don’t only use this method for images — since early 2017, all user-provided assets served by Marketplacer applications are served via this method. Non-image assets are now served via signed CloudFront links connecting to this S3 bucket.</p><p>We never remove assets from this S3 bucket (as storing small things in S3 is relatively cheap). The entire bucket is backed up to a server external to AWS every day.</p><p>Using SHA means that the chance of two different assets having the same name is effectively impossible. This means that each asset uploaded will never be replaced with a different one in the same location.</p><p>As we rely on signed links, and as the S3 bucket is private, we can even use this method to serve &amp; control access to paid content.</p><p>In conclusion:</p><ul><li>using S3 to store images, and ImgIx &amp; CloudFront to serve them, allows us to scale horizontally without using NFS to share files between servers</li><li>as images are stored in a single bucket, development &amp; test environments can link to them without worrying about missing content</li><li>there is no risk of development or test corrupting production data, as each image uploaded to S3 is named based on its content, making each individual asset effectively immutable</li><li>copying images from templates or between customers is now as simple as copying a string between database records</li><li>we only need to change the query parameters sent to ImgIx to change our web-optimisation method</li></ul><p><em>Originally published at </em><a href="http://mipearson.id.au/blog/20180603_cas"><em>mipearson.id.au</em></a><em>.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=6770a181879f" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Structured Logging for Rails using ELK]]></title>
            <link>https://medium.com/@mipearson/structured-logging-for-rails-using-elk-41fb94293e82?source=rss-b55649fdb439------2</link>
            <guid isPermaLink="false">https://medium.com/p/41fb94293e82</guid>
            <category><![CDATA[elk]]></category>
            <category><![CDATA[logging]]></category>
            <category><![CDATA[rails]]></category>
            <category><![CDATA[elasticsearch]]></category>
            <category><![CDATA[devops]]></category>
            <dc:creator><![CDATA[Michael Pearson]]></dc:creator>
            <pubDate>Thu, 05 Jul 2018 06:17:48 GMT</pubDate>
            <atom:updated>2018-07-05T22:21:36.767Z</atom:updated>
            <content:encoded><![CDATA[<p>This post describes the structured logging setup used at Marketplacer to publish information about each request to our Rails application to our ELK stack.</p><p>Our primary goal for our ELK platform was forensics &amp; long term usage analysis of back-office functionality. For example, we wanted to know:</p><ul><li>has this route or controller been used at all in the last six months?</li><li>how did this advert’s price get set to zero, and by who?</li><li>we’re seeing a sudden uptick in transactions per second every day at 1 AM — is it one of our API users, or is it a bot trying to scrape us?</li></ul><p>We needed to store everything we could about every request (including POST/PATCH parameters) and we needed to keep it for six months or longer. Storing only a fraction of the requests (as in an instrumentation platform like Google Analytics) or not storing the parameters of the request (as in traditional text log files) would not meet our goals.</p><p>We did not need to store detailed error information or debug output; we use <a href="https://rollbar.com/">Rollbar</a> for that.</p><p>Our solution was to write a log subscriber that would sit at the same level as the normal Rails request logger and write to its own log file to be ingested by our ELK stack. This log file would not replace or combine with the usual production.log or unicorn.stderr.log produced by our application. <a href="https://www.elastic.co/products/beats/filebeat">filebeat</a> (part of the ELK stack) would tail the file and send its contents to ur Elasticsearch logging server.</p><p>The solution is described below from bottom-up:</p><ul><li>how we obtain events &amp; emit log entries in Rails</li><li>how those events are sent to Elasticsearch via Filebeat</li><li>how Elasticsearch indexes those events via ingest pipelines</li><li>how we configure Kibana to display those events</li></ul><p>Some of the code &amp; Elasticsearch configuration used in the below has been made open source and is available in <a href="https://gist.github.com/mipearson/e363504be7792c8971b851954cceb61d">this gist</a>.</p><h3>Structured Output Format</h3><p>Our log subscriber outputs one line of JSON per request. We use JSON as it can then be directly ingested in to Elasticsearch with little to no modification. This makes it much more reliable and flexible than a more traditional human readable log file. A reformatted example follows:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/684/1*QJhgbWDA70cRRV5ZbsWF2Q.png" /></figure><p>The only attribute outside of the rails object is @timestamp, which is used by the ELK stack to order events. We provider our own timestamp as we don&#39;t want filebeat to use the timestamp at which the log file was read, but the time at which the event occurred, as they may not be exactly the same.</p><p>Inside the rails object:</p><ul><li>params contains all parameters that we can safely record or index, including parameters supplied as part of a PATCH/POST/PUT request</li><li>action and controller are duplicated from route to make it easier to search for them specifically within ELK</li><li>session_id is recorded partly so we can attempt to replay a user&#39;s actions from within ELK</li><li>original_path includes any query string parameters: this is primarily useful for discovering parameter decoding edge cases in our application or Rails itself</li></ul><h3>Structured Output Code</h3><p>The code used to generate this output is split in to two main sections: the subscriber itself, and a routine to flatten the parameters.</p><h3>Flattening Parameters</h3><p>Parameters in Rails can be represented internally as objects containing objects, eg:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/606/1*SzSw6nndnAIz94MIOFj0gw.png" /></figure><p>While we can insert this information directly into Elasticsearch, what we <em>can’t</em> then do is insert anything which contains the same key names but a different schema. For example, we can’t insert the above object and then insert another where advert is a single string instead of an object.</p><p>We work around this by flattening the parameters into a single object with many keys, eg:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/642/1*SH6O3rRfecFlOxw4ExHBXQ.png" /></figure><p>The flattener is also responsible for:</p><ul><li>trapping instances of Rack::Test::UploadedFile or Rack::Multipart::UploadedFile and representing them only as [FILE UPLOAD #{filename}]</li><li>truncating any string longer than 120 characters</li></ul><h3>Log Subscriber</h3><p>The log subscriber attaches itself to the ActionController on the process_action and redirect_to methods. process_action handles publishing the log event to ELK, whereas redirect_to sets a thread local variable for process_action to later pick up and register as a redirect.</p><p>process_action does the following:</p><ul><li>runs the request’s parameters through the flattener</li><li>attaches exception information, if present</li><li>attaches relevant headers (eg HTTP_HOST, HTTP_USER_AGENT, etc)</li><li>obtains a user ID and/or administrator ID from the session, if present</li><li>attaches overall, database and view runtimes</li><li>attaches route as a combination of controller and action to make searching easier in ELK</li><li>adds a @timestamp</li><li>encodes the result as JSON and emits it to the log</li></ul><p>Each line is written to log/elk.json.log and is picked up by <em>filebeat</em> running on the production system to be sent to our ELK stack.</p><h3>Filebeat</h3><p>Filebeat is part of the “beats” suite of software, published by Elasticsearch as part of their ELK stack. Filebeat reads logs files, applies some basic filtering, and sends the contents on to Elasticsearch.</p><p>It can be used as a lightweight replacement for a heavy logstash instance. It is an entire replacement for logstash-forwarder.</p><p>Each production server logs ELK events to its local filesystem, and thus one filebeat instance runs on each production server.</p><p>Our filebeat configuration contains entries for other things we ingest. I’ve replicated only the portions relevant to our Rails logging below:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/315/1*lGff8k9auhnxwI6dxOmIHw.png" /></figure><p>Note the following:</p><ul><li>we tell Elasticsearch to use the ingest pipeline named rails on each event</li><li>the events from elk.json.log are tagged rails, which means they&#39;re then sent to the logs-rails-* indices</li><li>json.keys_under_root means we treat each log entry as the entire event, rather than embedding its contents in a json object when we send it to Elasticsearch</li></ul><h3>Elasticsearch</h3><p>Apart from regular Elasticsearch configuration, there are two main things we had to consider when setting up ES to handle Rails log data:</p><ul><li>Ingest Pipelines</li><li>Index Templates</li></ul><p>Ingest pipelines transform the data before it is indexed. They can be used as a replacement for logstash transforms, and they even have the capability to understand logstash “grok” rules.</p><p>Index templates describe defaults for how new indexes are created, and both the format and limitations of the data to be added to the index. Elasticsearch can guess this based on the data, but it’s much safer to specify it ahead of time.</p><h3>Ingest Pipeline</h3><p>We created a simple ingest pipeline named rails. It uses the ingest-geoip and ingest-useragent plugins to find a location for the request&#39;s IP address and decode the HTTP User Agent respectively.</p><h3>Index Template</h3><p>Our index template for indices matching logs-* is based heavily on the defaults that <em>filebeat</em> provides for its indices, with some modifications:</p><ul><li>we limit the index to one shard and zero replicas, to save space on our single machine Elasticsearch setup</li><li>we copy the geoip and user_agent mapping definitions from the nginx-access default mappings into our rails section</li><li>we specify dynamic mapping rules for our rails parameters:</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/296/1*aRnfb9YwlYbH8DyG-0jtaQ.png" /></figure><h3>Kibana</h3><p>Once the data is in Elasticsearch we can use Kibana as a dashboard to analyze it. We found it useful to set up Kibana before setting up filebeat: its development tools allow for easy interaction with the Elasticsearch API.</p><p>Most of our interactions with Kibana are via the “Discover” tab. We use filters to identify long-term usage of site functionality or discover the series of events that led to an error. Right-clicking on a particular field also allows us to show a visualisation on that field: eg a breakdown of user agents or countries.</p><p>One big caveat with Kibana is that it can suffer when there are lots of different fields in your indexes, which is a problem we have. It’s occasionally unfortunately necessary to hard-restart Kibana as it enters a 100% CPU locked state.</p><p>Now that we have Kibana we can finally answer some of the questions raised above:</p><p>To find out if code is being used, we first add a filter against rails.route or rails.controller and then set the time range at the top of the page to one month.</p><p>To discover what happened to our bad advert, we can first try filtering rails.params.id for its ID and rails.method to limit results to POST requests. We then set the time range to when we suspect the incident occurred. If we find the relevant request, we can finally filter on rails.session_id to work out how they got to that point in our application.</p><p>To work out the origin of the extra transactions, we first set the time range to when those transactions are occurring. We can then create visualisations based on source IP address, destination controller, and GeoIP location to determine the nature of the traffic.</p><p><em>Originally published at </em><a href="http://mipearson.id.au/blog/20180705_elk/"><em>mipearson.id.au</em></a><em>.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=41fb94293e82" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[The Four Pillars of Motivation]]></title>
            <link>https://medium.com/@mipearson/the-four-pillars-of-motivation-ef9df6273767?source=rss-b55649fdb439------2</link>
            <guid isPermaLink="false">https://medium.com/p/ef9df6273767</guid>
            <category><![CDATA[productivity]]></category>
            <category><![CDATA[leadership]]></category>
            <category><![CDATA[management]]></category>
            <category><![CDATA[developer-productivity]]></category>
            <dc:creator><![CDATA[Michael Pearson]]></dc:creator>
            <pubDate>Mon, 16 Apr 2018 00:35:33 GMT</pubDate>
            <atom:updated>2018-04-16T00:35:33.796Z</atom:updated>
            <content:encoded><![CDATA[<p>As a developer, designer or other direct contributor to the product creation process, there’s a single principle that drives morale, productivity and motivation:</p><blockquote><em>I feel that I am </em><strong><em>effectively</em></strong><em> working on something I find </em><strong><em>interesting</em></strong><em> and </em><strong><em>meaningful</em></strong><em> in a </em><strong><em>safe</em></strong><em> environment.</em></blockquote><p>If these conditions are not at least mostly satisfied, other perks like team lunches, hack days or remote working options become less relevant. Annoyances like noisy open plan offices, frequent interruptions or a long commute have a greater effect.</p><p>It is not possible to completely satisfy all of these conditions for all contributors. Some of the items mentioned in the conditions are part of a healthy development process: I don’t recommend allowing every contributor to work on whatever technology they want or ignore QA or code reviews because it means they can work quicker! However, these conditions will help you understand and evaluate the consequences of policy &amp; process decisions you make as a leader.</p><h3>The Pillars</h3><p>Let’s break this down:</p><h4>Effective</h4><p>The contributor must be able to work without having to frequently pause or context-switch. Things that could cause the contributor to pause include:</p><ul><li>Slow tooling or development environment</li><li>Needing to always ask others for help on a complicated or confusing system</li><li>Lack of direction as to the thing the contributor is trying to change or implement</li><li>Unreliable test environments</li><li>Mandatory process (eg QA) that requires frequent interruptions</li></ul><p>When working on a long, complicated or even tedious task, personal momentum is critical to keep the contributor on task. Pauses interrupt that momentum and it becomes very easy to become distracted by unrelated tasks when having to wait for five minutes or more for a process to complete.</p><p>An effective contributor is one that feels that the time they spend leads to them making continuous progress on a task.</p><h4>Interesting</h4><p>I’ve found this condition to vary significantly between contributors. For some, “interesting” can mean working with the same technology for years, as long as the work is varied, and for others the inverse is true.</p><p>The contributor should feel that they are being intellectually challenged by the work they’re doing. This doesn’t need to be a constant: there’s always drudge work, and it’s up to you to make sure it’s spread relatively evenly.</p><p><a href="http://randsinrepose.com/archives/bored-people-quit/">“Bored People Quit”</a> by Rands is a great article on this topic, detailing how to detect whether people are interested in their work and how to effectively manage it.</p><h4>Meaningful</h4><p>The contributor should feel that the work they’re doing is going to somehow have a positive effect, somewhere.</p><p>This “somewhere” varies, but can include:</p><ul><li>making it easier for people in the company to do their jobs</li><li>increasing the company’s cashflow</li><li>making the world a better place</li></ul><p>It is very demoralising to spend weeks or months on a task to have it cancelled or have it be a commercial failure.</p><h4>Safe</h4><p>In my opinion this condition is the most critical of the four.</p><p>The contributor should feel that they’re working in a place of safety without risk of attack. They should feel that their position is secure, that their contributions aren’t going to be unfairly criticised, and that they’re not going to be personally attacked.</p><p>A lack of safety activates something deep in our lizard brains: it becomes almost impossible to remain focused or motivated.</p><p>Note that this doesn’t preclude structured criticism or healthy competition, but it’s up to you as a leader to guide your team to do this in a positive way.</p><h3>An Example</h3><p>Let’s talk about Bob. Bob’s working on a task to change a button colour from green to blue.</p><p>Bob’s spent two weeks on this task because there’s an overcomplicated theming framework underpinning the site’s colours which makes a simple task like this very difficult. Therefore, Bob does not feel <strong>effective</strong>. The theming framework is a mess of spaghetti code written by a previous developer. It is not <strong>interesting</strong> to work with. This is the second time Bob has been asked to make a colour change to this component, and he expects that the person asking for the change is going to change their mind again. He does not feel that his work is <strong>meaningful</strong>. Finally, Bob is being passive-aggressively pestered by his line manager, because how could a simple colour change take two weeks?! Bob does not feel <strong>safe</strong>.</p><p>Bob is unmotivated, unproductive and right now his morale is suffering. How you deal with this depends on the likelihood of this particular situation reoccuring and how difficult it would be to affect change. If this is an isolated incident it might be better to let Bob know about some more interesting &amp; relevant upcoming work. If its a continual problem, you’d need to attack this from two directions: inwards, devoting time to improving the themeing framework, and outwards, setting expectations with managers &amp; product owners regarding the difficulty of making colour changes.</p><h3>Autonomy</h3><p>One last thing I’d like to touch on is <strong>autonomy</strong>. Contributors must feel that they can improve their own environments such that these conditions are better met. For example, a contributor should be able to improve CI reliability &amp; speed to remove a blocker (to improve <strong>effectiveness</strong>), there should be some capacity for self-selection of <strong>interesting</strong> or <strong>meaningful</strong> work, and contributors should be able to move to a team that better fits their personality, allowing them to feel <strong>safer</strong>.</p><p>In conclusion, what I’ve detailed above isn’t a solution — it’s a mechanism for framing morale and motivation issues within your team, allowing you as a leader to make better decisions.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ef9df6273767" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How long are you spending in Capybara?]]></title>
            <link>https://medium.com/@mipearson/how-long-are-you-spending-in-capybara-81303f75389e?source=rss-b55649fdb439------2</link>
            <guid isPermaLink="false">https://medium.com/p/81303f75389e</guid>
            <category><![CDATA[performance]]></category>
            <category><![CDATA[ruby]]></category>
            <category><![CDATA[rspec]]></category>
            <category><![CDATA[capybara]]></category>
            <category><![CDATA[selenium-webdriver]]></category>
            <dc:creator><![CDATA[Michael Pearson]]></dc:creator>
            <pubDate>Wed, 14 Mar 2018 08:57:38 GMT</pubDate>
            <atom:updated>2018-03-18T20:47:55.025Z</atom:updated>
            <content:encoded><![CDATA[<p>Our full-system integration tests take too long to run: between five and eight minutes in a highly optimised CI environment, and over an hour if run on a developer’s laptop.</p><p>One of the ways we’re trying to manage this is by logging which tests take the longest and then printing them out at the end of the run, eg:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*1Ypc65rOI3yhzZJGo7nlNg.png" /></figure><p>In this particular run refunds_invoices_spec.rb is taking three minutes to complete. If we divide that by the eight workers on that CI instance, that’s adding a good 22 seconds to each run, assuming a perfect distribution of tests between workers.</p><p>We can dive further using rspec --profile:</p><pre>&gt; bundle exec rspec --profile -- spec/features/admin/refunds_invoices_spec.rb</pre><pre>    63.36 seconds ./spec/features/admin/refunds_invoices_spec.rb:45<br>    14.9 seconds ./spec/features/admin/refunds_invoices_spec.rb:642<br>    9.39 seconds ./spec/features/admin/refunds_invoices_spec.rb:372</pre><pre>...</pre><p>Unfortunately, the test case at line 45 is 329 lines long. There’s definitely ways we can optimise that, but without measuring exactly where in those lines it’s spending its time we have no way of knowing where the biggest impact will be.</p><p>We could measure where the problem areas are by adding lots of puts Time.now — start lines in at random points, but this isn’t our only problem test, and that method gets tiresome very quickly.</p><p>Instead, I’ve written a small rspec helper which wraps every Capybara DSL method and prints out how long each operation took. For example:</p><pre>&gt; CAPYBARA_TIMERS=1 bundle exec rspec spec/features/admin/refunds_invoices_spec.rb:45<br>Run options: include {:locations=&gt;{&quot;./spec/features/admin/refunds_invoices_spec.rb&quot;=&gt;[45]}}<br>3.64s spec/support/features/session_helpers.rb:8 visit &quot;/administration&quot;<br>0.73s spec/features/admin/refunds_invoices_spec.rb:46 visit &quot;/administration/refund_invoices&quot;<br>  0.02s spec/features/admin/refunds_invoices_spec.rb:48 assert_text &quot;Refunds&quot;<br>0.06s spec/features/admin/refunds_invoices_spec.rb:48 within_element &quot;h1.MPanelGroup-heading&quot;<br>0.11s spec/features/admin/refunds_invoices_spec.rb:50 fill_in &quot;Invoice ID&quot;<br>...</pre><p>The first column in the output is the time the operation took. The second is the filename and line number the Capybara method was called from. Third is the Capybara method itself, and the final column is the first argument.</p><p>At the end of the run we’re also given a total along with RSpec’s usual timing information, allowing us to see what percentage of the test’s time was spent in Capybara:</p><pre>CAPYBARA TOTAL 45.24s</pre><pre>Finished in 52.38 seconds (files took 3.14 seconds to load)</pre><p>Analysing the log we see a repeated pattern:</p><pre>...<br>0.04s spec/support/integration_helpers.rb:61 find &quot;thead th&quot;<br>0.24s spec/support/integration_helpers.rb:36 path Array<br>0.16s spec/support/integration_helpers.rb:63 path Array<br>0.03s spec/support/integration_helpers.rb:63 find Array<br>0.02s spec/features/admin/refunds_invoices_spec.rb:346 assert_text &quot;2018-03-19&quot;<br>0.05s spec/support/integration_helpers.rb:61 find &quot;thead th&quot;<br>0.16s spec/support/integration_helpers.rb:36 path Array<br>0.15s spec/support/integration_helpers.rb:63 path Array<br>0.02s spec/support/integration_helpers.rb:63 find Array<br>0.02s spec/features/admin/refunds_invoices_spec.rb:347 assert_text &quot;awaiting&quot;<br>...</pre><p>In this run we see this pattern at least 10 times. Looking at integration_helpers line 61 we find the following method, used for finding a particular cell in a table based on its column heading and row:</p><pre>def cell_for_column(text, row: 1)<br>  th = find(&#39;thead th&#39;, text: text, match: :prefer_exact)<br>  column = element_index(th)<br>  find(:xpath, &quot;#{th.path}/ancestor::table&quot;).find(:css, &quot;tbody tr:nth-of-type(#{row}) &gt; :nth-child(#{column})&quot;)<br>end</pre><p>This method calls .path twice and .find twice. Fortunately, if the element already exists on the page, .find is quite fast, but .path is taking between 100 and 300 ms per call.</p><p>I optimised the method to only use find calls and never call .path:</p><pre>def cell_for_column(text, row: 1)<br>  th = find(&#39;thead th&#39;, text: text, match: :prefer_exact)<br>  column = th.find(:xpath, &#39;..&#39;).all(&#39;th&#39;).index(th) + 1<br>  table = th.find(:xpath, &#39;ancestor::table&#39;)<br>  table.find(:css, &quot;tbody tr:nth-of-type(#{row}) &gt; :nth-child(#{column})&quot;)<br>end</pre><p>Re-running the spec with this version shaves off a good 15 seconds!</p><pre>...</pre><pre>0.04s spec/support/integration_helpers.rb:61 find &quot;thead th&quot;<br>0.01s spec/features/admin/refunds_invoices_spec.rb:346 assert_text &quot;2018-03-19&quot;<br>0.05s spec/support/integration_helpers.rb:61 find &quot;thead th&quot;<br>0.01s spec/features/admin/refunds_invoices_spec.rb:347 assert_text &quot;awaiting&quot;<br>...</pre><pre>CAPYBARA TOTAL 26.72s</pre><pre>Finished in 36.31 seconds (files took 3.21 seconds to load)</pre><p>The code to track time spent in Capybara is embedded below. Simply drop it in your spec/support folder in your Rails project and preface your spec run with CAPYBARA_TIMERS=1</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/c0d43c6ecdb803270ecfb12117d9cd70/href">https://medium.com/media/c0d43c6ecdb803270ecfb12117d9cd70/href</a></iframe><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=81303f75389e" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Four Tools That Let Me Love Javascript]]></title>
            <link>https://medium.com/@mipearson/four-tools-that-let-me-love-javascript-6e111583f289?source=rss-b55649fdb439------2</link>
            <guid isPermaLink="false">https://medium.com/p/6e111583f289</guid>
            <category><![CDATA[es6]]></category>
            <category><![CDATA[flow]]></category>
            <category><![CDATA[babel]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[react]]></category>
            <dc:creator><![CDATA[Michael Pearson]]></dc:creator>
            <pubDate>Fri, 25 Aug 2017 04:09:05 GMT</pubDate>
            <atom:updated>2017-08-25T04:23:14.234Z</atom:updated>
            <content:encoded><![CDATA[<p>I’ve traditionally thought of myself as a backend developer: my career, before management, was in Java, C, Perl, Python and Ruby. I admit to scoffing at the idea of Javascript as a “real” language as late as 2011, even though some amazing work was being done with it in the previous decade.</p><p>Recently, I realised that I was <em>really enjoying</em> writing Javascript. This came as a complete surprise to me, which says a lot more about me than it does about Javascript.</p><p>I’m now going to tell you about four tools that make Javascript an actual joy to program with in 2017.</p><h3>React</h3><p>When I first heard about it, I wasn’t sold. “HTML in your Javascript? I thought we all decided that was a terrible idea!” It was <a href="https://www.youtube.com/watch?v=nEdJvQIt0P4">this talk</a> by <a href="https://twitter.com/deoxxa">Conrad Pankoff</a> presented at <a href="http://iv.campjs.com/">CampJS IV</a> in 2014 that brought me around.</p><p>What I love about React is the unidirectional information flow. I think that’s because I am a backend developer: in Rails, you load something from a database, muck with it a bit, and then render it in a view. Your view is entirely a product of a particular set of a data, rather than something that’s built up over time. React’s the same: the HTML that is generated by the JSX is entirely dependant on the component’s properties and state.</p><p>Effectively, this makes it much easier for the developer to reason through how the component will appear in response to different interactions.</p><h3>Babel</h3><p>For me, <a href="https://babeljs.io/learn-es2015/">ES2015 and onward</a> resolve many of the problems I had with Javascript back when I first started working with it in 2005. It adds language features that make it much easier to control flow, work with objects, and define classes.</p><p>Babel means that I can use those features today. The great thing about Babel when compared to tools that compile to Javascript and offer better constructs is that I can have the confidence that what I’m writing today will still be supported tomorrow — it’s just a newer version of Javascript, and eventually I might not even need Babel.</p><h3>ESLint</h3><p>ESLint is my favourite linter for one reason: its documentation. With other linters I quite often find that it’ll tell me off for doing something but not offer me a constructive way to resolve that problem.</p><p>ESLint, on the other hand, prints an easily-googlable rule name along with each warning, and the documentation for that rule often lists workarounds or conditions where the rule shouldn’t apply.</p><p>For example, I was recently hit by <a href="https://github.com/yannickcr/eslint-plugin-react/blob/master/docs/rules/no-unescaped-entities.md">react/no-unescaped-entities</a> as I added doesn&#39;t (note apostrophe) to some JSX I was writing. The documentation not only goes in to <em>why</em> that&#39;s a problem, but also gave me a workaround: use &amp;apos;.</p><h3>Flow</h3><p>This could have easily been TypeScript, but I learned Flow first, and it felt like a better fit for our existing project.</p><p>Flow was the last piece of the puzzle: on adding it to the stack, I suddenly realised I was really enjoying working with Javascript.</p><p>The obvious thing I love about Flow is that it gives me confidence when working with large projects in Javascript. I’d worked with statically typed languages before, so it wasn’t hard for me to immediately see the benefits. My team were convinced when I showed them a common mistake — changing the core type of an object attribute in one file and having it error on another — and how quickly Flow would let you see that you’d done something wrong.</p><p>The less obvious thing I love about Flow is that you can have the best of both worlds: by using the <a href="https://flow.org/en/docs/types/any/">any</a> type, you can effectively prototype code as you would dynamically, and then later treat the any typedefs as TODOs and correct them when you have more confidence in your architecture.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=6e111583f289" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>