<?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 Chad Wilken on Medium]]></title>
        <description><![CDATA[Stories by Chad Wilken on Medium]]></description>
        <link>https://medium.com/@chadwilken?source=rss-fa20f9abac0a------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*8kE6kA-UL2IHxkvB.jpeg</url>
            <title>Stories by Chad Wilken on Medium</title>
            <link>https://medium.com/@chadwilken?source=rss-fa20f9abac0a------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sun, 29 Nov 2026 21:05:01 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@chadwilken/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[Elegant PDFs from User-Generated Content in React]]></title>
            <link>https://medium.com/companydev/elegant-pdfs-from-user-generated-content-in-react-656b79533fee?source=rss-fa20f9abac0a------2</link>
            <guid isPermaLink="false">https://medium.com/p/656b79533fee</guid>
            <category><![CDATA[draftjs]]></category>
            <category><![CDATA[react]]></category>
            <dc:creator><![CDATA[Chad Wilken]]></dc:creator>
            <pubDate>Tue, 03 Mar 2020 03:46:54 GMT</pubDate>
            <atom:updated>2021-08-18T20:02:04.945Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*hagj64DTsBsngfXq" /><figcaption>Photo by <a href="https://unsplash.com/@karsten_wuerth?utm_source=medium&amp;utm_medium=referral">Karsten Würth</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>Converting user generated HTML into a PDF has always been a pain. You’re stuck with solutions like <a href="https://wkhtmltopdf.org/">wkhtmltopdf</a>, <a href="https://coderwall.com/p/5vmo1g/use-phantomjs-to-create-pdfs-from-html">PhantomJS</a>, or <a href="https://developers.google.com/web/updates/2017/04/headless-chrome#create_a_pdf_dom">Headless Chrome</a>. The problem I have found with all of these tools is that they are either slow, fail to match styles, or require running on a server. At CompanyCam we allow our users to generate reports, some of which are hundreds of pages long. No matter how you slice it, that makes any of the options above much more difficult, especially if you allow the user to preview their PDF.</p><p>In this post we will look at how we use a combination of React PDF, DraftJS, and Redraft to craft a PDF from user-generated content that is instantly available in the user’s browser for preview and download.</p><p>Since we use several libraries I think it may be helpful to give a quick overview and what each library is used for.</p><h3>React PDF</h3><p><a href="https://react-pdf.org/">React PDF</a> is a PDF renderer built for React. It includes several components that represent different aspects of a PDF document such as a Document, Page, and View. It can output to a file on the server or a Blob in the browser. It provides an interface for layout, styling, and asset fetching.</p><h3>DraftJS</h3><p><a href="https://draftjs.org/">DraftJS</a> describes itself as a “Rich Text Editor Framework for React”. Draft was developed by Facebook and is extremely flexible and extensible.</p><h3>Redraft</h3><p>[Redraft] is a middleman of sorts and renders the output from DraftJS, allowing you to override the default elements that correspond with different <em>blocks</em>.</p><h3>React-PDF</h3><p>No, this isn’t a duplicate. Confusingly, it has a similar name, but it a completely different library. <a href="https://github.com/wojtekmaj/react-pdf">React-PDF</a> is a library to display PDFs on the web as an svg or canvas. As a tip, this library <strong>doesn&#39;t</strong> have a &quot;@&quot; in the name.</p><h3>The Flow</h3><p>CompanyCam allows users to build reports using photos they’ve captured in our app. Users can add comments using a WYSIWYG editor and optionally choose if they want to display metadata such as when the photo was captured, who took the photo, and the project it belongs to.</p><p>When the user selects to generate a PDF of a report we launch a modal and finish fetching the pages of entries. Once we have the data we can get down to work. We pass the report to our PDF component, which is responsible for bootstrapping some libraries, generating a PDF and converting it to a blob, and then rendering the preview.</p><p>We start by passing our Document component to the pdf function imported from @react-pdf/renderer. The Document component will be shown later, for now know that it uses @react-pdf components to represent entires in the report.</p><pre>import { pdf } from ‘@react-pdf/renderer’;</pre><pre>Const PDF = ({ report }) =&gt; {<br>  const [loading, setLoading] = useState(true);<br>  const [documentURL, setDocumentURL] = useState();<br>  Const [numPages, setNumPages] = useState(0);</pre><pre>  useEffect(<br>    () =&gt; {<br>      const generateBlob = async () =&gt; {<br>        setLoading(true);<br>        const blob = await pdf(<br>          &lt;Document report={report} imageSize={imageSize} /&gt;,<br>        ).toBlob();<br>        setLoading(false);<br>        setDocumentURL(window.URL.createObjectURL(blob));<br>      };</pre><pre>      if (report) {<br>        generateBlob();<br>      } else {<br>        setLoading(false);<br>        setDocumentURL(null);<br>      }<br>    },<br>    [report],<br>  );<br>};</pre><p>We await the pdf function and then call toBlob to get a <a href="https://developer.mozilla.org/en-US/docs/Web/API/Blob">Blob</a> object. We generate a URL for the blob using URL.createObjectURL and then store that in the state. We can use the URL of the blob to render a preview of the document and to allow the user to download the file.</p><pre>import { pdfjs, Document as PDFDocument, Page as PDFPage } from ‘react-pdf’;</pre><pre>pdfjs.GlobalWorkerOptions.workerSrc = `//cdnjs.cloudflare.com/ajax/libs/pdf.js/${pdfjs.version}/pdf.worker.js`;</pre><pre>const PDF = ({ report }) =&gt; {<br>  // PDF generation omitted here.</pre><pre>  if (loading) {<br>    return &lt;Spinner message=&quot;Fetching Images&quot; /&gt;;<br>  }</pre><pre>  return (<br>    &lt;React.Fragment&gt;<br>      {loading &amp;&amp; &lt;div&gt;Rendering PDF…&lt;/div&gt;}<br>      &lt;div&gt;<br>        &lt;a<br>          href={documentURL}<br>          className=&quot;ccb-blue-small&quot;<br>          style={{ margin: ‘auto 0 0’ }}<br>          download={filename}<br>        &gt;<br>          Download PDF<br>        &lt;/a&gt;<br>      &lt;/div&gt;<br>      &lt;PDFDocument<br>        file={documentURL}<br>        onLoadSuccess={(result) =&gt; setNumPages(result.numPages)}<br>        loading={&lt;Spinner /&gt;}<br>      &gt;<br>        &lt;PDFPage<br>          renderMode=&quot;svg&quot;<br>          pageNumber={currentPage}<br>        /&gt;<br>      &lt;/PDFDocument&gt;<br>    &lt;/React.Fragment&gt;<br>  );<br>}</pre><p>Once we have the documentURL generated by @react-pdf we can render a preview using react-pdf. We pass the PDFDocument component the documentURL as the file. Once the document has loaded it will call onLoadSuccess and tell us some info such as how many pages the PDF contains. Inside of that, we pass a PDFPage component and tell it to either render using a canvas or svg and which page we want to display.</p><p>You will notice that we can pass the documentURL as the href and a filename to the download prop for the a tag and it will download the blob with the filename specified. This is handy because the user can instantly download the generated PDF.</p><p>I omitted the code that shows how we change the page for brevity. The code is a simple click handler that increments or decrements the currentPage variable making sure it stay in bounds.</p><p>At this point we know how to render and display the Document component, but what does Document <em>do</em> and how do we convert HTML to @react-pdf components?</p><h3>Document Rendering and Content Conversion</h3><p>React-PDF handles almost everything for you out of the box so the Document component is fairly simple.</p><pre>import {<br>  Document as PDFDocument,<br>  StyleSheet,<br>  Page,<br>  Font,<br>} from ‘@react-pdf/renderer’;<br>import PageFooter from ‘./PageFooter’;<br>import CoverPage from ‘./CoverPage’;<br>import Entry from ‘./Entry’;</pre><pre>Font.register({<br>  family: ‘Public Sans’,<br>  fonts: [<br>    { src: ‘https://cdn.companycam.com/fonts/PublicSans-Regular.ttf’ },<br>    {<br>      src: ‘https://cdn.companycam.com/fonts/PublicSans-SemiBold.ttf’,<br>      fontWeight: 700,<br>    },<br>  ],<br>});</pre><pre>// Allow users to include emojis in markup<br>Font.registerEmojiSource({<br>  format: ‘png’,<br>  url: ‘https://twemoji.maxcdn.com/2/72x72/‘,<br>});</pre><pre>const styles = StyleSheet.create({<br>  // omitted for brevity<br>});</pre><pre>const Document = ({ report }) =&gt; {<br>  const { <br>    entries, <br>    settings, <br>  photoCount,<br>    company,<br>    title,<br>    subtitle,<br>    createdAt,<br>    featuredEntry<br>  } = report;</pre><pre>  const { name, logoLargeUrl } = company;<br>  const featuredPhoto = featuredEntry.assetPreviewLarge;</pre><pre>  return (<br>    &lt;PDFDocument&gt;<br>      &lt;Page style={pageStyles} size=&quot;LETTER&quot;&gt;<br>        &lt;PageFooter title={title} /&gt;<br>        &lt;CoverPage<br>          companyName={name}<br>          logo={logoLargeUrl}<br>          title={title}<br>          subtitle={subtitle}<br>          createdAt={createdAt}<br>          featuredPhoto={featuredPhoto}<br>          photoCount={photoCount}<br>        /&gt;<br>      &lt;/Page&gt;<br>      &lt;Page style={pageStyles} size=&quot;LETTER&quot;&gt;<br>        &lt;PageFooter title={title} /&gt;<br>        {entries.map((entry) =&gt; {<br>          return (<br>            &lt;Entry<br>              key={entry.id}<br>              entry={entry}<br>              settings={settings}<br>            /&gt;<br>          );<br>        })}<br>      &lt;/Page&gt;<br>    &lt;/PDFDocument&gt;<br>  );<br>};</pre><pre>export default Document;</pre><p>The wrapping component is a Document component imported from @react-pdf. All components inside of this component must be a @react-pdf component.</p><p>The Page, CoverPage and PageFooter are all self explanatory so I won’t show the code. We render a page at the beginning of the document that includes the company&#39;s name and title of the report. We then render an Entry for each item in the report. The interesting part here is that we wrap all entries in a single Page component. React PDF has a pretty advanced layout engine. If the content is going to overflow the page, it will wrap to a new page. You can also pass a break prop to add a page break before the component being rendered.</p><p>I’ve included the Entry component for completeness. The only interesting part is that it renders a RichText component.</p><pre>import React from &#39;react&#39;;<br>import { StyleSheet, View, Image, Text, Link } from &#39;@react-pdf/renderer&#39;;<br>import RichText from &#39;../RichText&#39;;</pre><pre>const styles = StyleSheet.create({<br>  // ...omitted<br>});</pre><pre>const Entry = ({ entry }) =&gt; {<br>  const { item, pageBreak } = entry;<br>  const { assetPreview } = item;</pre><pre>  return (<br>    &lt;View style={containerStyles} wrap={false} break={pageBreak}&gt;<br>      &lt;Link<br>        src={assetPreviewLarge}<br>        style={imageContainerStyles}<br>        target=&quot;_blank&quot;<br>      &gt;<br>        &lt;Image<br>          style={imageStyles}<br>          source={{<br>            uri: assetPreview,<br>            headers: { Pragma: &#39;no-cache&#39;, &#39;Cache-Control&#39;: &#39;no-cache&#39; },<br>          }}<br>        /&gt;<br>      &lt;/Link&gt;<br>      &lt;View style={contentStyles}&gt;<br>        &lt;RichText note={entry.notes} /&gt;<br>      &lt;/View&gt;<br>    &lt;/View&gt;<br>  );<br>};</pre><pre>export default Entry;</pre><h3>Redraft Meet React PDF</h3><p>So far, most of the code I have shown you isn’t anything earth shattering. I included it so you could have a better understanding of the hierarchy and flow. In the RichText component we actually do some more interesting work.</p><pre>import {<br>  EditorState,<br>  ContentState,<br>  convertToRaw,<br>  convertFromHTML,<br>} from ‘draft-js’;<br>import redraft from ‘redraft’;</pre><pre>const RichText = ({ note }) =&gt; {<br>  const blocksFromHTML = convertFromHTML(note);<br>  const initialState = ContentState.createFromBlockArray(<br>    blocksFromHTML.contentBlocks,<br>    blocksFromHTML.entityMap,<br>  );</pre><pre>  const editorState = EditorState.createWithContent(initialState);<br>  const rawContent = convertToRaw(editorState.getCurrentContent());</pre><pre>  return redraft(rawContent, renderers, { blockFallback: ‘unstyled’ });<br>};</pre><pre>export default RichText;</pre><p>The component is quite simple; it handles converting the HTML to a format that is understood by DraftJS using convertFromHTML.</p><blockquote><em>If you’re using DraftJS to generate the HTML, you can store the raw JS object from Draft using </em><em>convertToRaw while editing.</em></blockquote><p>Once we have converted the HTML into <em>blocks</em>, we initialize a ContentState and an EditorState. We do all of that to finally get the rawContent. The raw content is a regular ole’ JS object. I recommend you log it to the console so you can see how parseable the data is. Finally we’re at the cool part, we return the result of calling redraft with the rawContent, renderers, and some options.</p><h3>Renderers</h3><p>The renderers object is a object that maps from the original type to the new component. Redraft uses the renderers object and iterates over the blocks, inline elements, and entities in the raw JS object, calling the corresponding function based on the type. DraftJS <a href="https://draftjs.org/docs/advanced-topics-custom-block-render-map">supports a handful of elements out of the box</a>, so we make a compatible React PDF component for each of the types that we support. Let’s take a look at our renderers:</p><pre>import { StyleSheet, View, Text, Link } from ‘@react-pdf/renderer’;</pre><pre>const renderers = {<br>  inline: {<br>    // The key passed here is just an index based on rendering order inside a block<br>    BOLD: (children, { key }) =&gt; {<br>      return (<br>        &lt;Text key={`bold-${key}`} style={{ fontWeight: 700 }}&gt;<br>          {children}<br>        &lt;/Text&gt;<br>      );<br>    },<br>    ITALIC: (children, { key }) =&gt; {<br>      return (<br>        &lt;Text key={`italic-${key}`} style={{ fontStyle: ‘italic’ }}&gt;<br>          {children}<br>        &lt;/Text&gt;<br>      );<br>    },<br>    UNDERLINE: (children, { key }) =&gt; {<br>      return (<br>        &lt;Text key={`underline-${key}`} style={{ textDecoration: ‘underline’ }}&gt;<br>          {children}<br>        &lt;/Text&gt;<br>      );<br>    },<br>  },<br>  /**<br>   * Blocks receive children and depth<br>   * Note that children are an array of blocks with same styling,<br>   */<br>  blocks: {<br>    unstyled: (children, { keys }) =&gt; {<br>      return children.map((child, index) =&gt; {<br>        return (<br>          &lt;View key={keys[index]}&gt;<br>            &lt;Text style={styles.text}&gt;{child}&lt;/Text&gt;<br>          &lt;/View&gt;<br>        );<br>      });<br>    },<br>    ‘header-one’: (children, { keys }) =&gt; {<br>      return children.map((child, index) =&gt; {<br>        return &lt;HeadingOne key={keys[index]}&gt;{child}&lt;/HeadingOne&gt;;<br>      });<br>    },<br>    ‘unordered-list-item’: (children, { depth, keys }) =&gt; {<br>      return (<br>        &lt;UnorderedList key={keys[keys.length - 1]} depth={depth}&gt;<br>          {children.map((child, index) =&gt; (<br>            &lt;UnorderedListItem key={keys[index]}&gt;{child}&lt;/UnorderedListItem&gt;<br>          ))}<br>        &lt;/UnorderedList&gt;<br>      );<br>    },<br>    ‘ordered-list-item’: (children, { depth, keys }) =&gt; {<br>      return (<br>        &lt;OrderedList key={keys.join(‘|’)} depth={depth}&gt;<br>          {children.map((child, index) =&gt; (<br>            &lt;OrderedListItem key={keys[index]} index={index}&gt;<br>              {child}<br>            &lt;/OrderedListItem&gt;<br>          ))}<br>        &lt;/OrderedList&gt;<br>      );<br>    },<br>  },<br>  /**<br>   * Entities receive children and the entity data<br>   */<br>  entities: {<br>    // key is the entity key value from raw<br>    LINK: (children, data, { key }) =&gt; (<br>      &lt;Link key={key} src={data.url}&gt;<br>        {children}<br>      &lt;/Link&gt;<br>    ),<br>  },<br>};</pre><p>As you can see we return a text element for all of the inline styles and apply the appropriate styles to match the type. For each of the blocks we created our own components that have applied styles to match the formatting required. For example, here is HeaderOne:</p><pre>const styles = StyleSheet.create({<br>  headingOne: {<br>    marginBottom: 4,<br>    color: ‘#3a4b56’,<br>    fontWeight: 700,<br>    fontFamily: ‘Public Sans’,<br>    lineHeight: 1.35,<br>    fontSize: 12,<br>  },<br>});</pre><pre>const HeadingOne = ({ children }) =&gt; {<br>  return (<br>    &lt;View&gt;<br>      &lt;Text style={styles.headingOne}&gt;{children}&lt;/Text&gt;<br>    &lt;/View&gt;<br>  );<br>};</pre><p>It a simple Text component wrapped in a View. By default a View will span the full width of the parent. Think of this is a block element in HTML.</p><p>One of the more interesting components is for lists. React PDF doesn’t have a built in component for ordered or unordered lists, so we made our own. Boiling it down, a list is just a block element with nested block elements prefixed with either a number or bullet before the entry.</p><pre>const styles = StyleSheet.create({<br>  list: {<br>    marginBottom: 8,<br>    marginLeft: 6,<br>  },<br>  listItem: {<br>    marginBottom: 4,<br>  },<br>  listItemText: {<br>    color: ‘#6b7880’,<br>    fontFamily: ‘IBM Plex Serif’,<br>    fontSize: 10,<br>    lineHeight: 1.45,<br>  },<br>});</pre><pre>const UnorderedList = ({ children, depth }) =&gt; {<br>  return &lt;View style={styles.list}&gt;{children}&lt;/View&gt;;<br>};</pre><pre>const UnorderedListItem = ({ children }) =&gt; {<br>  return (<br>    &lt;View style={styles.listItem}&gt;<br>      &lt;Text style={styles.listItemText}&gt;<br>        • &amp;nbsp;&lt;Text&gt;{children}&lt;/Text&gt;<br>      &lt;/Text&gt;<br>    &lt;/View&gt;<br>  );<br>};</pre><pre>const OrderedList = ({ children, depth }) =&gt; {<br>  return &lt;View style={styles.list}&gt;{children}&lt;/View&gt;;<br>};</pre><pre>const OrderedListItem = ({ children, index }) =&gt; {<br>  return (<br>    &lt;View style={styles.listItem}&gt;<br>      &lt;Text style={styles.listItemText}&gt;<br>        {index + 1}. &amp;nbsp;&lt;Text&gt;{children}&lt;/Text&gt;<br>      &lt;/Text&gt;<br>    &lt;/View&gt;<br>  );<br>};</pre><p>And there you have it. You have taken user input, parsed it using DraftJS and converted it into elements that can be styled and rendered using React PDF. Implementing new types is as easy as adding a new entry in renderers and styling it.</p><p>One place I would like to try using Redraft is to render React Native components from HTML instead of relying on a web view in our mobile app.</p><p>For the full code from the example you can check out <a href="https://gist.github.com/chadwilken/caa6d945b5d5505fe1788f53af2be244">this gist</a>.</p><p>If you want to work on features like this <a href="https://grnh.se/abeb334d3us">CompanyCam is hiring</a>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=656b79533fee" width="1" height="1" alt=""><hr><p><a href="https://medium.com/companydev/elegant-pdfs-from-user-generated-content-in-react-656b79533fee">Elegant PDFs from User-Generated Content in React</a> was originally published in <a href="https://medium.com/companydev">CompanyDev</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Turbolinks, Stimulus, and React Oh My!]]></title>
            <link>https://medium.com/companydev/turbolinks-stimulus-and-react-oh-my-83541d69c41?source=rss-fa20f9abac0a------2</link>
            <guid isPermaLink="false">https://medium.com/p/83541d69c41</guid>
            <category><![CDATA[turbolinks]]></category>
            <category><![CDATA[stimulus]]></category>
            <category><![CDATA[rails]]></category>
            <category><![CDATA[react]]></category>
            <dc:creator><![CDATA[Chad Wilken]]></dc:creator>
            <pubDate>Thu, 12 Apr 2018 20:10:09 GMT</pubDate>
            <atom:updated>2018-04-12T20:12:25.909Z</atom:updated>
            <content:encoded><![CDATA[<p><a href="https://companycam.com/">CompanyCam’s</a> web app has changed considerably over the years. Starting as a .NET app packed with tons of jQuery plugins 🤮 before moving onto a Backbone Marionette app 🤢. About a year ago I rewrote the entire web app as a single-page React application that consumed our REST API. This works <em>well</em>, but sometimes React is overkill for simple CRUD actions.</p><p>The team at CompanyCam is small, we have to optimize where we can to stay small and still achieve our goals. This is what spurred me thinking about how to optimize our productivity and maintain our happiness 😁.</p><p>After a little investigation, I began tinkering with moving the mundane items to regular ole’ Rails ERB templates and re-enabling <a href="https://github.com/turbolinks/turbolinks">Turbolinks</a>. This was simple enough to start with but I found myself needing to add some functionality such as multi-select drop-downs with autocompletion. Using JavaScript plugins with Turbolinks is a bit more difficult than binding to the page load event and initializing the plugin. Turbolinks loads subsequent pages using AJAX and replaces the page body with the response. Wouldn’t it be nice if you could just know when an element was added to the page and initialize any plugins that the element(s) needed? <em>Queue the mystical harp music 🎶</em>.</p><p>This is when I reached for <a href="https://stimulusjs.org/">Stimulus</a>, a new framework from Basecamp that uses the MutationObserver API to listen to changes in the DOM and connecting it with a JavaScript object. When a new element is inserted, such as a new body from Turbolinks or a div from server-generated JavaScript, Stimulus looks for the elements that have a `data-controller` attribute and links the element with the corresponding controller. This may not seem powerful at first, but it allowed me to write a small snippet of code once and use it for all of the multi-selects in the future. This is that code:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/f6c6e29590b2b41dccc421d4fea1e54d/href">https://medium.com/media/f6c6e29590b2b41dccc421d4fea1e54d/href</a></iframe><p>This controller takes an existing select tag and converts it into a select2 instance, affording you all of the handy features of select2. The problem is that Turbolinks will cache the current page before navigating to a new page, which we don’t want. That is why we have the event listener for turbolinks:before-cache that gets the values from select2 and marks the corresponding option(s) as selected in HTML before unmounting the select2 plugin. The next time you navigate to the page, this controller’s function is called again and select2 is remounted.</p><p>We also have one for hiding the flash messages from Rails after a short delay. The controller below is very simplistic, but you get the idea.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/c6780fee72dc22b6870bc25776e97285/href">https://medium.com/media/c6780fee72dc22b6870bc25776e97285/href</a></iframe><p>As you can see, Stimulus is pretty useful and compliments Turbolinks very well.</p><p>Everything so far is fine and dandy, but what about the complex or extremely dynamic features we already have built in React? Well, that was the last piece I needed to figure out. I ended up pulling a bit of inspiration from react-rails and created a helper to render an element on the page containing the name of the React component and any props JSON stringified.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/3689cc80e2dcec89c014f45877cf8d6b/href">https://medium.com/media/3689cc80e2dcec89c014f45877cf8d6b/href</a></iframe><p>You’ll notice that it is creating an emptydiv, but it also adds a few data tags to hook it up with Stimulus. Stimulus can then take over and mount the React component when the element is detected on the page. The Stimulus controller is as simple as:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/200b46dd4d157236038fa5cc6b3d3dc7/href">https://medium.com/media/200b46dd4d157236038fa5cc6b3d3dc7/href</a></iframe><p>When the element is rendered on the page Stimulus will lookup the React component out of a global object, get any props from the element, call ReactDOM.render, and then add an event listener for turbolinks:before-cache to unmount the component before changing pages. The beauty once again is that you can have as many of these elements on a page as you want and each will be rendered and unmounted separately.</p><p>This hasn’t been tested in production yet, but I plan to try it out on beta once I get it a bit further along. Local testing, however, shows positive results and has been quite easy to work with as I migrate the React views back to Rails templates.</p><p>If you have any questions or have built something similar to this, let me know in the comments below.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=83541d69c41" width="1" height="1" alt=""><hr><p><a href="https://medium.com/companydev/turbolinks-stimulus-and-react-oh-my-83541d69c41">Turbolinks, Stimulus, and React Oh My!</a> was originally published in <a href="https://medium.com/companydev">CompanyDev</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Speedy JSON Endpoints with Rails]]></title>
            <link>https://medium.com/companydev/speedy-json-endpoints-with-rails-b6130f757815?source=rss-fa20f9abac0a------2</link>
            <guid isPermaLink="false">https://medium.com/p/b6130f757815</guid>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[json]]></category>
            <category><![CDATA[rails]]></category>
            <category><![CDATA[api]]></category>
            <dc:creator><![CDATA[Chad Wilken]]></dc:creator>
            <pubDate>Wed, 26 Jul 2017 16:05:15 GMT</pubDate>
            <atom:updated>2017-07-26T16:05:15.824Z</atom:updated>
            <content:encoded><![CDATA[<p>CompanyCam is a service to store photos by projects for contractors and other industries that work at a lot of different places. Our goal is to provide as much information as possible to our users at a glance. This often means pulling in information from multiple models, potentially filtered based on the current user’s permissions or settings.</p><p>When most people think of the performance issues of a large object graph, they think about the cost to query the information out of the database. They pay special attention to avoid things like n+1 queries or loading too much information, which can slow the app to a halt. Yes, this is useful, but in our case, that wasn’t the bottleneck — our issue was Active Model Serializers which had mediocre caching and wouldn’t use the eagerly loaded associations.</p><p>In this post I will discuss our decision to move from Active Model Serializers to the <a href="https://github.com/amatsuda/jb">jb gem</a>. The jb gem allowed us to vastly improve caching, reduction of n+1 queries, and most importantly our response time.</p><h3>Some Context</h3><p>Let’s get a better understanding of the object graph and why some things were so slow when using AMS. Take a look at the main screen of our mobile app.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/406/1*r-EdYnSnYoIVUwnHBDq6tA.jpeg" /><figcaption>Project Feed Cards</figcaption></figure><p>In case it isn’t apparent at first glance, we are pulling in the project name, number of photos at the project, the 6 most recent photos at the project, who took the last photo, and on some screens we show how many photos have been taken that day. Then repeat that 50 times (one for each card in the page of projects). The query was difficult to get optimized (we can save that for another post), but the serialization was still taking an average of 500–700ms and some all the way up to 2,500ms. Using <a href="http://scoutapp.com/">Scout</a> we were able to see that this was because Active Model Serializers was causing a n+1 query when rendering instead of using the eager loaded associations.</p><p>I did a bit of research and stumbled on a issue thread on GitHub where user’s were saying that sometimes caching made things <em>slower</em>. I happened to stumble across an article talking about <a href="https://github.com/amatsuda/jb">jb</a>, a gem that uses Rails view rendering with partials to make it faster than other options like JBuilder. The added benefit is that it allows easily caching partials and will use eagerly loaded associations instead of triggering additional queries. It also provides access to all of your view helpers, so methods like current_user are accessible to your JSON view and you don’t have to provide a serialization_scope like you do with AMS.</p><h3>How It Works</h3><p>The gem adds itself as a render handler so that it will check in the directory matching the controller path with the json.jb extension. If you want to render a template that doesn’t follow the Rails lookup default you can specify render ‘path/to/your/template.json.jb To start, let’s look at our index.json.jb template to see how we get render a collection of projects.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/1c97c596d0757df63946ce8f5c2fa5a4/href">https://medium.com/media/1c97c596d0757df63946ce8f5c2fa5a4/href</a></iframe><p>We simply call map on projects, which means that this view will return an Array of projects. For each project we first check to see if it has a cached version we can load to avoid unnecessary rendering. You will notice we are adding ‘v1’, ‘recent’, and then whether or not the user can see all users photos (a permission) to the cache key so that this project is used only in this context since the contents are unique. Then for each project we render the project partial. Notice we are following the Russian doll caching method.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/3d201d7c816b970d6ac9d2be8f38ae67/href">https://medium.com/media/3d201d7c816b970d6ac9d2be8f38ae67/href</a></iframe><p>The beauty of this is that you are simply constructing and returning an object that can be used as valid JSON, in our case this is a Hash. This gives you nearly unlimited freedom on how you construct your JSON object.</p><h3>So What’s the Result?</h3><p>With these few simple changes we were able to reduce our average request time for the controller from 500ms to just <em>50ms! </em>That is <em>10x </em>faster and only took 30 minutes to implement<em>. </em>Needless to say, I am extremely pleased with these results. Not to mention the reduced load on the database is a free bonus.</p><h3>Where to Now?</h3><p>It is so simple migrating an Active Model Serializers class to the new jb view that anytime I see a controller with slow responses due to AMS I can spend 15 minutes converting it. I have already moved a handful of other controller endpoints to the new method and have noticed significant increase in speed and reduction in load on the database.</p><p>If you have any stories about complete object graph rendering I would love to hear about them in the comments below.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b6130f757815" width="1" height="1" alt=""><hr><p><a href="https://medium.com/companydev/speedy-json-endpoints-with-rails-b6130f757815">Speedy JSON Endpoints with Rails</a> was originally published in <a href="https://medium.com/companydev">CompanyDev</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Useful Tips for React Native]]></title>
            <link>https://medium.com/@chadwilken/useful-tips-for-react-native-391b4e08a7a6?source=rss-fa20f9abac0a------2</link>
            <guid isPermaLink="false">https://medium.com/p/391b4e08a7a6</guid>
            <category><![CDATA[ios]]></category>
            <category><![CDATA[react-native]]></category>
            <category><![CDATA[react]]></category>
            <dc:creator><![CDATA[Chad Wilken]]></dc:creator>
            <pubDate>Fri, 29 Apr 2016 18:59:58 GMT</pubDate>
            <atom:updated>2016-04-29T18:59:58.236Z</atom:updated>
            <content:encoded><![CDATA[<p>We recently decided to revamp our app using React Native. Other than reading a few articles I was very unfamiliar with React/React Native. From my initial research I knew we wanted to use something like Alt.js or Redux to manage state. We ended up going with Redux and heavily watched <a href="https://egghead.io/series/getting-started-with-redux">Dan’s talk on egghead</a>. This gave us a glimpse into how to get started, but Todo apps are only useful to base your app on when they have simple data structures. We then decided to look at Facebook’s F8 app, which was <a href="http://makeitopen.com/">made open-source</a>. This gave us a better understanding about more complex data. I think that everyone just starting out with React, React Native, or Redux should look at all of these examples as they come from the people with the best knowledge of the tools. These are useful but I want to show you a few other items that we find helpful or useful to know.</p><h4>Remote Debugging</h4><p>Running your app on a simulator is pretty simple and works pretty well out of the box. If however you want to run your code on a device it requires setting up a tunnel to your computer or connecting directly to your computer using its IP address. At CompanyCam we use <a href="http://forwardhq.com/">forward</a> for a lot of things and this is one of them. We set the location of our JavaScript based on if you we are in development (DEBUG) or production. In our app delegate we choose where to load the code from checking if there is a DEBUG symbol:</p><pre><em>AppDelegate.m</em></pre><pre>NSURL *jsLocation;<br>#if DEBUG<br>  NSString *url = [[[NSBundle mainBundle] infoDictionary] stringForKey:@”REACT_SERVER_URL”];<br>  jsLocation = [NSURL URLWithString:url];<br>#else<br>  jsLocation = [[NSBundle mainBundle] URLForResource:@”main” withExtension:@”jsbundle”];<br>#endif</pre><p>The value that we set for the <em>REACT_SERVER_URL</em> value in <em>Info.plist</em> is our url from Forward but with “<em>react-</em>” and the user’s name embedded in it:</p><pre>https://react-${USER}-companycam.fwd.wf:8081/</pre><p>The USER flag is set by Xcode and matches the output of <em>whoami</em>, which is coincidentally what we use in your Procfile. “What is a Procfile used for you?” may be asking. In this case the Procfile is used by <a href="https://github.com/ddollar/foreman">foreman</a>, a tool I use for nearly every project. Foreman allows you to have a set of commands in a given Procfile and it runs each of them. To start running our app we have a single command:</p><pre>foreman start</pre><p>This runs every command in our Procfile which is only two in our case:</p><pre><em>Procfile</em></pre><pre>react: (JS_DIR=`pwd`/app; cd node_modules/react-native; npm run start — — root $JS_DIR)<br>forward: forward 8081 react-`whoami`</pre><p>Now launch on your phone and simulator and see them work together.</p><h4>Redux</h4><p>When we started using Redux I was like “ok, this looks cool. How do I use it in a big app though?”. Luckily Facebook kicks ass and open-sourced their <a href="http://makeitopen.com/">F8 app</a> this year. The also did a nice <a href="http://makeitopen.com/tutorials/building-the-f8-app/data/">write-up</a> on integrating data with your app. This was useful, but at the end of the day playing around with the tools is what made me comfortable with it. At first I wanted to set an array as the value of a root key in the global app state when using <em>combineReducers. </em>After a bit of messing around I realized this wasn’t possible. Once you come to grips with the fact that if you create a reducer for say users, companies, and groups and join them using <a href="http://redux.js.org/docs/api/combineReducers.html"><em>combineReducers</em></a><em>l</em>, you are going to have a global state with the keys “users”, “companies”, and “groups”. Anything returned from the respective reducer will be a key under that root key. In our case we store a key “all” and a key “filtered” for each leaving our global state looking something like:</p><pre>{<br>  &quot;users&quot;: {<br>    &quot;all&quot;: [<em>user1, user2, etc...</em>],<br>    &quot;filtered&quot;: [<em>id1, id2, etc...</em>]<br>  },<br>  &quot;groups&quot;: {<br>    <em>...same<br></em>  },<br>  &quot;companies&quot;: {<br>    <em>...same<br></em>  }<br>}</pre><p>Then in components that care about a specific part of the state you can use the <em>connect</em> function provided by <a href="https://github.com/reactjs/react-redux">react-redux</a> and provide it a function that is called each time the state is updated so it can update the components props.</p><pre><em>GroupDetails.js</em></pre><pre>class GroupDetails extends React.Component {<br>  <em>...code omitted<br></em>}</pre><pre><em>state is the apps global state object when using Redux<br></em>const mapStateToProps = (state, ownProps) =&gt; {<br>  return {<br>    users: state.users.all,<br>    group: state.groups.all.filter((group) =&gt; { return group.id === ownProps.groupId })<br>  }<br>}</pre><pre>export default connect(mapStateToProps)(GroupDetails)</pre><p>Now whenever the state gets updated this component will be notified and will be able to update it’s <em>users</em> and <em>group props.</em></p><p>This is just the tip of the interesting things that we have found so far. I would like to hear things that you have learned that makes React/React Native development easier once it clicks. If you have some, leave them in the comments.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=391b4e08a7a6" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Dipping Your Toes into React Native]]></title>
            <link>https://medium.com/companydev/dipping-your-toes-into-react-native-6570528d3711?source=rss-fa20f9abac0a------2</link>
            <guid isPermaLink="false">https://medium.com/p/6570528d3711</guid>
            <category><![CDATA[react]]></category>
            <category><![CDATA[react-native]]></category>
            <category><![CDATA[ios]]></category>
            <dc:creator><![CDATA[Chad Wilken]]></dc:creator>
            <pubDate>Fri, 15 Apr 2016 18:24:56 GMT</pubDate>
            <atom:updated>2017-07-26T16:12:46.792Z</atom:updated>
            <content:encoded><![CDATA[<p>When I took over as CTO at CompanyCam we had a universal app written in Xamarin that was horrendous. My first call was to rewrite both apps natively for Android and iOS using Java and Objective-C/Swift respectively. Upon completion the performance of the apps improved and the bugs decreased significantly.</p><p>A constant problem as a small startup is that you are always short on developers. In our case this meant our apps varied in the features they provided. On top of handling our webapp, I also write our iOS app, which for our users means that Android gets features late if at all.</p><h4>Benefits of React Native</h4><p>In case you aren’t familiar with React Native some benefits include:</p><ul><li>The node/npm ecosystem: Use packages provided by npm allowing you to write less code. This also allows you to write your own packages for use across iOS/Android.</li><li>Hot Reloading: As soon as you save your file it reloads on the device; in most cases it preserves your spot and state in the app.</li><li>Flexbox: Let your designers do their thing and style the app using technologies they are already familiar with. The flexbox model is a little different but Jared, our designer, figured it out in 10 minutes.</li><li>Chrome Debug Tool: You can debug your code and log to the console from within your JS.</li><li>Easy of Integration: It is almost too easy integrating it with an existing app. Add <em>RCT_EXPORT_MODULE();</em> to the file and expose methods you would like to call from JS with <em>RCT_EXPORT_METHOD.</em></li><li>It’s just JavaScript: If you have team members familiar with JavaScript they can start to contribute to iOS and Android. Granted some parts require some knowledge of the platform, but in general they don’t.</li></ul><h4>Testing the Waters</h4><p>To test how easy it was to integrate we decided to rewrite our login screen in React Native. The screen is fairly simple and looks like:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/375/1*o0PhOzFOCgTtpKIu9djqRg.jpeg" /></figure><p>The trick with this is that for now we wanted to keep using our API helper to make the HTTP requests. To make that function we added:</p><pre>RCT_EXPORT_METHOD(startLoginWithUsername:(NSString *)username password:(NSString *)password callback:(RCTResponseSenderBlock)callback). </pre><p>The callback allows us to perform work that may take an undetermined amount of time. One thing to note is that this method gets called off of the main thread so if you require the main thread use:</p><pre>dispatch_async(dispatch_get_main_queue(), ^{/* Code here */});</pre><p>This will allow you to do whatever you need on the main thread. Calling this method from React is as simple as creating a function in your component that is called when the user performs a specific action, in our case tapping the “Sign In” button. Our function looks like:</p><pre>submitForm = () =&gt; {<br>  // Get the class you exposed with RCT_EXPORT_MODULE();<br>  var LoginViewController = NativeModules.LoginViewController;</pre><pre>  // Method are changed to parameters for the JS function<br>  LoginViewController.startLoginWithUsername(this.state.email, this.state.password, function() {<br>     console.log(‘Login Failed’);<br>   });<br> }</pre><p>In our case since this is our first screen written in React Native. If the login is successful we replace the current view controller with a native iOS view controller. However, if the call fails we show an alert and then call the callback allowing us to clear the password field.</p><p>One of my favorite parts is that React Native is intuitive and makes simple things simple. For example, when a user taps to enter text into a textfield on native iOS you are required to manually calculate the height of the keyboard and then adjust scrollview contents to accommodate scrolling the textfield back into view. React Native handles this nearly automatically by using:</p><pre>let scrollResponder = this.refs.scrollView.getScrollResponder();<br>scrollResponder.scrollResponderScrollNativeHandleToKeyboard(<br>  React.findNodeHandle(this.refs[refName]), // The ref of the input<br>  110, //additionalOffset<br>  true<br>);</pre><p>That small snippet of code handles everything that used to require calculating heights, modifying layout constraints and scrollview content sizes.</p><h4>Wrap Up</h4><p>I know this doesn’t seem overly complex or dynamic, but that is the point! We wanted to take a simple screen and see how easy it was to do marginally complex tasks such as working with native Objective-C. We are getting ready to do a major over-hall of our app and are planning on using React Native to speed it up. Our long term goal is to share most of the code between our iOS and Android apps.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=6570528d3711" width="1" height="1" alt=""><hr><p><a href="https://medium.com/companydev/dipping-your-toes-into-react-native-6570528d3711">Dipping Your Toes into React Native</a> was originally published in <a href="https://medium.com/companydev">CompanyDev</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Getting Sexy with Core Data]]></title>
            <link>https://medium.com/companydev/getting-sexy-with-core-data-b009fab6e9b1?source=rss-fa20f9abac0a------2</link>
            <guid isPermaLink="false">https://medium.com/p/b009fab6e9b1</guid>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[ios]]></category>
            <category><![CDATA[core-data]]></category>
            <dc:creator><![CDATA[Chad Wilken]]></dc:creator>
            <pubDate>Thu, 29 Oct 2015 14:27:49 GMT</pubDate>
            <atom:updated>2015-10-29T14:27:49.262Z</atom:updated>
            <content:encoded><![CDATA[<p>Recently I was tasked with updating the way we we’re using <em>Core Data</em> in our application. The app was using the legacy concurrency type of NSConfinementConcurrencyType. When you use this to initialize your NSManagedObjectContext you are <em>guaranteeing</em> that you will access this context from the correct thread, if you do not, sorry Charlie it’s a <strong>crash</strong>. Some people still use this method and in fact if you call [[NSManagedObjectContext alloc] init], this is the default concurrency type selected. You may have a single threaded application or do very minimal work on a background thread, and if so, then this could work for you. Sure, in the old setup it is possible to do a lot of work in the background, and in fact we do a lot of it. Currently we have a method that creates a new context for use on a background thread like:</p><pre>- (NSManagedObjectContext *)backgroundContext { <br>  NSPersistentStoreCoordinator *coordinator = [self persistentStoreCoordinator]; <br>  NSManagedObjectContext *bgContext = nil; <br>  if (coordinator != nil) { <br>    bgContext = [[NSManagedObjectContext alloc] init]; <br>    [bgContext setPersistentStoreCoordinator:coordinator]; <br>  } <br>  <br>  [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(objectContextDidSave:)  name:NSManagedObjectContextDidSaveNotification bgContext]; </pre><pre>  return bgContext; <br>}</pre><p>Then in objectContextDidSave: you merge in the changes to your main managed object context on the main thread. The problem with this, is that you can still perform disk IO on the main thread, blocking the UI, and potentially taking long enough that it is painfully noticeable.</p><p>Apple introduced a nice feature in iOS 5, <em>parent/child contexts</em> as well as a concurrency model that <em>guarantees</em> if you execute your code inside a block passed to performBlock: or performBlockAndWait: that it will use the correct queue. The new concurrency options you can initialize a NSManagedObjectContext with are NSPrivateQueueConcurrecyType and NSMainQueueConcurrencyType. When you select the NSPrivateQueueConcurrencyType and call performBlock: or performBlockAndWait: on this context it will <strong>automatically</strong> use the correct queue, so the thread you call this from does not matter. Keep in mind that the thread you call this from doesn’t matter, but you still have to abide by the rules of the NSManagedObject not being <em>thread-safe</em>. The NSMainQueueConcurrencyType is for use on the main queue, which is used by the <em>main thread</em>.</p><h3>Parent/Child Contexts</h3><p>Back to parent and child contexts. These allow you to have a NSManagedObjectContext belong to another NSManagedObjectContext, sharing its persistentStoreCoordinator and thus persistentStore. This my friends is where the fun begins <em>(if you are nerdy and thing Core Data is fun like me)</em>.</p><p>Setting a NSManagedObjectContext instance as a child context of another instance is as easy as assigning its parentContext property to the context you wish to be the parent. The beauty of setting the context as a child is that <strong>it doesn’t persist its changes to disk</strong>. Instead it pushes its changes up to its parent but still triggers a NSManagedObjectContextDidSaveNotification. You can observe this notification and perform a <strong>save on the parentContext writing the changes to disk</strong>.</p><p>The benefit of this setup comes when you use a specific arrangement for the parent and the child contexts. We have a single parent context of type NSPrivateQueueConcurrencyType and this context is associated with the persistent store coordinator, we call this property the privateQueueManagedObjectContext. We keep this context private to the CoreDataController class since it is more of an implementation detail. We then have one public NSMainQueueManagedObjectContext property named mainQueueManagedObjectContext that is a <strong>child</strong> of our privateQueueManagedObjectContext, all changes from the mainQueueManagedObjectContext are pushed up to the privateQueueManagedObjectContext and <strong>written to disk on the private queue using a background thread</strong>. This is hugely beneficial by allowing you to save the mainQueueManagedObjectContext on the main thread and having it be very efficient since it is simply pushing its changes to the privateQueueManagedObjectContext and not actually writing to disk! Let’s take a look at the code to get this setup:</p><pre>- (instancetype)init { <br>  NSPersistentStoreCoordinator *psc = [[NSPersistentStoreCoordinator alloc] initWithManagedObjectModel:self.managedObjectModel];<br>  NSError *error = nil; <br>  NSPersistentStore *store = [psc addPersistentStoreWithType:self.storeType configuration:self.modelConfiguration URL:self.storeURL options:self.storeOptions error:&amp;error]; <br>  <br>  NSAssert(store, @&quot;error creating the core data stack, perhaps the managed object model changed?&quot;); <br>  if(store == nil) { <br>    NSLog(@&quot;error creating core data stack: %@&quot;, error); <br>    return nil; <br>  } <br>  <br>  _privateQueueManagedObjectContext = [[NSManagedObjectContext alloc] initWithConcurrencyType:NSPrivateQueueConcurrencyType]; <br>  _privateQueueManagedObjectContext.mergePolicy = NSMergeByPropertyObjectTrumpMergePolicy; <br>  _privateQueueManagedObjectContext.persistentStoreCoordinator = psc; </pre><pre>  [_privateQueueManagedObjectContext performBlock:^{    <br>    [[_privateQueueManagedObjectContext userInfo] setValue:@&quot;Private Queue&quot; forKey:@&quot;mocIdentifier&quot;]; <br>  }]; </pre><pre>  _mainQueueManagedObjectContext = [[NSManagedObjectContext alloc] initWithConcurrencyType:NSMainQueueConcurrencyType]; <br>  _mainQueueManagedObjectContext.mergePolicy = NSMergeByPropertyObjectTrumpMergePolicy; <br>  _mainQueueManagedObjectContext.parentContext = _privateQueueManagedObjectContext; <br>  [[_mainQueueManagedObjectContext userInfo] setValue:@&quot;Main Thread&quot; forKey:@&quot;mocIdentifier&quot;]; <br>  <br>  NSNotificationCenter *defaultCenter = [NSNotificationCenter defaultCenter]; <br>  [defaultCenter addObserver:self selector:@selector(handleManagedObjectContextDidSaveNotification:) name:NSManagedObjectContextDidSaveNotification object:nil]; <br>  [defaultCenter addObserver:self selector:@selector(saveMasterContext) name:NSManagedObjectContextDidSaveNotification object:_mainQueueManagedObjectContext];<br>}</pre><p>When the <em>mainQueueManagedObjectContext</em> fires a NSManagedObjectContextDidSaveNotification it will call the saveMasterContext method which essentially just calls save on the <em>privateQueueManagedObjectContext</em> and persists the changes to disk. We will take a look at the handleManagedObjectContextDidSaveNotification: method called by the observer in a moment but first I want to talk about <em>worker contexts</em>.</p><h3>Worker Contexts</h3><p>We use <em>worker contexts</em> to perform all sorts of operations in the background. Their lives can be short and that is fine since we only need them temporarily. However, we do need to know about the changes that they made so we can update our <em>privateQueueManagedObjectContext</em>. We created a helper method to create a new worker context</p><pre>- (NSManagedObjectContext *)backgroundContext <br>{ <br>  NSManagedObjectContext *context = [[NSManagedObjectContext alloc] initWithConcurrencyType:NSPrivateQueueConcurrencyType]; <br>  context.parentContext = self.privateQueueManagedObjectContext; <br>  context.mergePolicy = NSMergeByPropertyObjectTrumpMergePolicy; <br>  [context performBlock:^{ <br>    [[context userInfo] setValue:@&quot;Child Context&quot; forKey:@&quot;mocIdentifier&quot;]; <br>  }]; <br>  <br>  [self.contextDirectory addObject:context]; return context; <br>}</pre><p>We don’t want to add ourselves as an observer of this context’s save notification since we will never be able to remove ourself as the observer. As you can see the way we initialize the background context is similar to the <em>mainQueueManagedObjectContext</em> except that this is also of the type NSPrivateQueueConcurrencyType. This allows us to have multiple contexts working in the background on different tasks such as importing data or asynchronously inserting data fetched from our API. You may notice we are adding this context to the <em>contextDirectory</em>. The <em>contextDirectory</em> is a NSHashTable, a collection that holds weak references to the objects added to it. We use this <em>contextDirectory</em> to decide if we should merge the changes into the <em>mainQueueManagedObjectContext</em> by ensuring the context triggering the notification exists in the directory.</p><p>The same rules apply when this context saves, its changes are pushed into the <em>privateQueueManagedObjectContext</em>. These however are not immediately written to disk, so how does it make it there?</p><h3>Writing Changes to Disk</h3><p>Now we can take a look at the handleManagedObjectContextDidSaveNotification: method that is called whenever a NSManagedObjectContextDidSaveNotification is fired on any object.</p><pre>- (void)handleManagedObjectContextDidSaveNotification:(NSNotification *)notification { NSManagedObjectContext *context = [notification object]; if (![self.contextDirectory containsObject:context] || context == self.mainQueueManagedObjectContext) { return; } [self.mainQueueManagedObjectContext performBlockAndWait:^{ [self.mainQueueManagedObjectContext mergeChangesFromContextDidSaveNotification:notification]; }]; [self saveMasterContext]; }</pre><p>As you can see this method ensures that the context that triggered the notification is included in the <em>contextDirectory</em> and that it isn’t the <em>mainQueueManagedObjectContext</em>. If it passes the initial checks then it merges in the changes to the <em>mainQueueManagedObjectContexts</em> inside a performBlockAndWait call, ensuring it happens on the correct queue. Once this finishes we go ahead and call saveMasterContext which in fact persists the changes to disk using the <em>privateQueueManagedObjectContext</em>.</p><p>Just so you can see the full implementation here is the saveMasterContext method:</p><pre>- (void)saveMasterContext { <br>  UIBackgroundTaskIdentifier identifier = [[UIApplication sharedApplication] beginBackgroundTaskWithName:@&quot;background-moc-save&quot; expirationHandler:^{ <br>    if([self.delegate respondsToSelector:@selector(coreDataController:didSaveWithError:)])<br>    { <br>      NSError *error = [NSError errorWithDomain:@&quot;com.modi&quot; code:3009 userInfo:@{NSLocalizedDescriptionKey : @&quot;Failed to save before background task expired&quot;}]; <br>      [self.delegate coreDataController:self didSaveWithError:error];<br>    } <br>  }]; <br>  <br>  [self.privateQueueManagedObjectContext performBlockAndWait:^{ <br>    if ([self.privateQueueManagedObjectContext hasChanges]) <br>    { <br>      NSError *error = nil; [self.privateQueueManagedObjectContext save:&amp;error]; <br>      if([self.delegate respondsToSelector:@selector(coreDataController:didSaveWithError:)])      { [self.delegate coreDataController:self didSaveWithError:error]; <br>      } </pre><pre>      NSLog(@&quot;saved background context&quot;); <br>    } </pre><pre>    [[UIApplication sharedApplication] endBackgroundTask:identifier]; <br>  }]; <br>}</pre><p>We begin by starting a background task, this is because we call this method when we receive a notification that the application is going to enter the background. We then call performBlockAndWait: with a block that checks to see if the <em>privateQueueManagedObjectContext</em> has changes and if so triggering a save and notifying our delegate if necessary. After everything is saved and done, we end the background task.</p><p>All of the code above I placed in a singleton class named CoreDataController that exposes helper methods to create worker contexts, get the <em>mainQueueManagedObjectContext</em> and that is about it. All of the nitty gritty details are hidden away inside of the class without a need to be known by outsiders.</p><p>Do you have other examples of successful Core Data stacks? I would love to take a look at what you have.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b009fab6e9b1" width="1" height="1" alt=""><hr><p><a href="https://medium.com/companydev/getting-sexy-with-core-data-b009fab6e9b1">Getting Sexy with Core Data</a> was originally published in <a href="https://medium.com/companydev">CompanyDev</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Postgres JSON Column Type in Rails 4]]></title>
            <link>https://medium.com/companydev/postgres-json-column-type-in-rails-4-24add6e0daa9?source=rss-fa20f9abac0a------2</link>
            <guid isPermaLink="false">https://medium.com/p/24add6e0daa9</guid>
            <category><![CDATA[rails]]></category>
            <category><![CDATA[ruby-on-rails]]></category>
            <dc:creator><![CDATA[Chad Wilken]]></dc:creator>
            <pubDate>Thu, 29 Oct 2015 14:20:42 GMT</pubDate>
            <atom:updated>2015-10-29T14:20:42.612Z</atom:updated>
            <content:encoded><![CDATA[<p>In recent days I have been starting a new project using Rails of course and hit a unique issue. I was needing to store arbitrary data with each record, that would likely be different for <em>each</em> record. I thought about using MongoDB for this project but didn’t feel that it was necessary since Postgres is always adding awesome new features.</p><p>At first glance ,<em>and Google search</em>, I thought about using the <a href="http://edgeguides.rubyonrails.org/active_record_postgresql.html#hstore">hstore extension</a>. However, this stores all values as strings and I needed to store all different types of data. Enter <em>JSON</em>, we all love JSON so why not store it in the database? Using JSON with Postgres doesn’t even require an extension and is supported out of the box with Rails 4+. Just use the json column type in your migration when creating or modifying tables. You can now store all sorts of complex data types as long as it is valid json.</p><pre>class User &lt; ActiveRecord::Base <br>end <br>#let&#39;s say our json column is named settings </pre><pre>me = User.create(name: &#39;Chad&#39;, settings: {notifications: [{email: true, sms:false}], profile_color: &#39;#ccc&#39;})</pre><p>This will save the json as you provide it, most importantly keeping the <em>values</em> as the same <em>data type</em>. Now when you retrieve the User’s settings from the you will be able to use all of the corresponding enumerable methods on them.</p><pre>me.settings.each_key { |key| puts me.settings[key] } <br>#Outputs {&quot;email&quot;=&gt;true, &quot;sms&quot;=&gt;false} #ccc</pre><p>I’m curious about some interesting uses you have found for the <em>json</em> column type, let me know about them in the comments.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=24add6e0daa9" width="1" height="1" alt=""><hr><p><a href="https://medium.com/companydev/postgres-json-column-type-in-rails-4-24add6e0daa9">Postgres JSON Column Type in Rails 4</a> was originally published in <a href="https://medium.com/companydev">CompanyDev</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[The Great Shift — ASP.NET to Rails]]></title>
            <link>https://medium.com/companydev/the-great-shift-asp-net-to-rails-4fecb8d87026?source=rss-fa20f9abac0a------2</link>
            <guid isPermaLink="false">https://medium.com/p/4fecb8d87026</guid>
            <category><![CDATA[aspnet]]></category>
            <category><![CDATA[ruby-on-rails]]></category>
            <category><![CDATA[rails]]></category>
            <dc:creator><![CDATA[Chad Wilken]]></dc:creator>
            <pubDate>Thu, 29 Oct 2015 14:19:11 GMT</pubDate>
            <atom:updated>2015-10-29T14:19:11.293Z</atom:updated>
            <content:encoded><![CDATA[<p>Several months ago I started as the CTO of <a href="http://companycam.com/">CompanyCam</a>, a location based photo management solution for contractors. The founder hired a local dev shop to create a web, iOS, and Android app, this infrastructure became my new working code base. I am a Ruby advocate and so I began looking for ways to get this to the more nimble and open Ruby ecosystem.</p><p>In this post I will cover how I migrated our API from a .NET backend to a Rails backend, keeping functionality and using the existing SQL Server Database.</p><p>Some ASP.NET fans may be screaming at their Nokia Lumia’s right now “why would you ever move from <em>ASP.NET</em> to <em>Rails</em>?”, so I will address this first.</p><h3>Why Switch?</h3><p>For some people, this question may be a no-brainer, but for others it may not be so apparent. C# and ASP.NET is a powerful language and has <em>some</em> great use cases. It is powerful and is used by many large sites such as <a href="http://stackoverflow.com/">stackoverflow</a> and my previous employer <a href="http://hudl.com/">Hudl</a>. I needed to rewrite the existing API already since it was miserable to work with. My main gripes with ASP.NET for a startup are the following:</p><ul><li>Speed of Development</li><li>Cost</li><li>Windows Server</li><li>Automated Deployments</li></ul><p>I’ll address each one of these below.</p><h4>Speed of Development</h4><p>One of my biggest complaints is constantly re-compiling my source code to test a single change. I’m aware you can work around it, but it isn’t as easy as it is in Ruby. Rails using <em>Spring</em> to reload your code on each run during development, which is nice to say the least.</p><p>We integrate with several services, some of which had a NuGet package, but most did not. This required me to write several of my own API wrappers. On the Ruby side, most of the services provided a gem to use, making integration must faster and more stable.</p><p>Let’s face it, C# is verbose. For example, our image uploading and resizing code shrunk from several hundred lines of code to about 75 lines in Ruby. It was also easier to follow and read.</p><h4>Cost</h4><p>Everyone <em>loves</em> paying licensing fees right? Of course not. Now I know we can, and we did, get Microsoft BizSpark. This is only good for a year and if you meet certain requirement. After that expires we can enjoy expensive licenses for Visual Studio, Windows Server, and every other piece of the Microsoft pie.</p><p>The new backend runs on Ubuntu, Ruby, Rails, and uses several other open source pieces of software. For a <em>IDE/editor</em> I use Sublime Text or Atom, the latter of which is free. Eventually we will migrate to Postgres for the database. The grand total for all of that <strong>$0</strong>, now that I can get on board with.</p><h4>Windows Server</h4><p>Some people love a <a href="https://en.wikipedia.org/wiki/Graphical_user_interface">GUI</a> when managing a server. I personally prefer to have my server admin tasks automated using <a href="https://www.chef.io/">Chef</a> and <a href="http://capistranorb.com/">Capistrano</a>. The only intervention I have with the server is adding SSL keys and setting enviroment variables.</p><h4>Automated Deployments</h4><p>Deploying to Windows is a chore, from my research you basically write your own software to deploy your webapp, or manually FTP everything to the server and restart it when you’re finished. I would rather stand on the shoulders of giants and use Capistrano. With Capistrano I can run a single command to deploy code, migrate the database, concatenate and minify assets, and restart the items needing restarted upon completion.</p><h3>Preparation &amp; Concerns</h3><p>We wanted to Rails piece by piece, so we chose to move the API that drives our iOS and Android apps first. This allows us to ensure that everything is working well and after we feel comfortable we can begin porting the rest over bit-by-bit. Not only that, but once the API is setup, we can begin to consume the new API form the existing webapp using jQuery or Backbone!</p><p>My main concern was how I was going to use the SQL Server database from the Rails api. After a bit of digging I found a great gem <a href="https://github.com/rails-sqlserver/activerecord-sqlserver-adapter">activerecord-sqlserver-adapter</a>. The setup was basically non-existent, I had to change a few settings in the database.yml file and it was done.</p><p>After figuring out the database I wasn’t sure how I was going to integrate authentication, it turned out to be fairly easy. I chose to use <a href="https://github.com/NoamB/sorcery">Sorcery</a> and a custom encryption provider. I chose Sorcery, because it adds just enough sugar without overwhelming your codebase like Devise.</p><p>I had to tweak a few settings in the sorcery initializer:</p><pre>Rails.application.config.sorcery.configure do |config| <br>  # We allow username or email address for auth<br>  user.username_attribute_names = [:Username, :EmailAddress]<br>  user.email_attribute_name = :EmailAddress<br>  user.crypted_password_attribute_name = :Passhash<br>  user.custom_encryption_provider = LegacyEncryptionProvider<br>  user.encryption_algorithm = :custom <br>end</pre><p>The main take away from the code above is the LegacyEncryptionProvider which is a class that has encrypt and matches? class methods. Which are extremely simple:</p><pre>def self.encrypt(*tokens) <br>  Digest::SHA256.base64digest(tokens.join(&quot;&quot;).encode(&#39;UTF-16LE&#39;)) end <br>def self.matches?(crypted, *tokens) <br>  crypted == Digest::SHA256.base64digest(tokens.join(&quot;&quot;).encode(&#39;UTF-16LE&#39;)) <br>end</pre><p>The <em>UTF-16LE</em> encoding is what C# uses when you use UnicodeEncoding#GetBytes</p><p>The .NET backend had some different user levels that acted as a permission set a.k.a authorization, so for this I decided to choose <a href="https://github.com/elabs/pundit">Pundit</a>. It gave me the flexibility required to ensure only proper user levels could perform certain actions in the controllers.</p><h3>To the Code Cave Batman</h3><h4>Models</h4><p>To begin I ran rake db:schema:dump to populate the <em>schema.rb</em> file with the existing database structure. The tables and columns were all <em>CamelCased</em>, which I wanted to convert to <em>snake_case</em> to match ruby and my personal preferences. I also needed to inform the model of its table name since Rails wasn’t going to be able to infer it automatically. An example model class looks like:</p><pre>class Image &lt; ActiveRecord::Base <br>  self.table_name = &quot;Images&quot; <br>  self.primary_key = &quot;ImageId&quot; <br>  has_many :image_comments, foreign_key: :ImageId, inverse_of: :image <br>  has_many :image_gallery_images, foreign_key: :ImageId, inverse_of: :image <br>  has_many :image_galleries, through: :image_gallery_images<br>  belongs_to :location, foreign_key: :LocationId, inverse_of: :images <br>  belongs_to :company, foreign_key: :CompanyId, inverse_of: :images  <br>  belongs_to :user, foreign_key: :UploadedById, inverse_of: :images</pre><pre>  accepts_nested_attributes_for :image_comments <br>  alias_attribute :id, :ImageId <br>  alias_attribute :active, :IsActive <br>  alias_attribute :filename, :Filename <br>  alias_attribute :date_uploaded, :DateUploaded <br>  alias_attribute :user_id, :UploadedById <br>  alias_attribute :notes, :Notes <br>  alias_attribute :location_id, :LocationId <br>  alias_attribute :lat, :Lat alias_attribute :lon, :Lon <br>  alias_attribute :company_id, :CompanyId <br>  alias_attribute :anonymous, :IsAnnonymousLocation <br>  alias_attribute :update_ticks, :UpdateTicks <br>  alias_attribute :url_large, :FullSizeUrl <br>  alias_attribute :url_medium, :WebSizeUrl <br>  alias_attribute :url_small, :MobileSizeUrl <br>  alias_attribute :image, :FullSizeUrl <br>  alias_attribute :date_received, :DateReceived <br>  <br>  before_validation :set_defaults, on: :create <br>  validates :filename, :date_uploaded, :user_id, :location_id, :lat, :lon, :company_id, :url_large, :url_medium, :url_small, presence: true </pre><pre>  private <br>  def set_defaults <br>    self.active = true <br>    self.date_received = DateTime.now.utc <br>  end <br>end</pre><p>At the top you can see where I set the <em>table_name</em> and <em>primary_key</em> attributes for the model. You will also notice a call to alias_attribute for each column in the database.</p><p>One caveat of using alias_attribute is that some code will require you to reference the column by the name in the schema. For example, look at association at the top of the class.</p><h4>Controllers</h4><p>Since we were going to be using this as an API first I wanted to namespace everything to make separating API controllers from the eventual view controller easier. I started by following most of <a href="https://labs.kollegorna.se/blog/2015/04/build-an-api-now/">this great up to date post</a>. This gave the basics for RESTful authentication and some default methods that allowed returning errors much more simple.</p><p><strong>Note:</strong> If you also follow the guide above, I recommend choosing your version of ActiveModelSerializers carefully. Basically avoid version 0.9.x since it is a random version. Use either 0.8.x or master (0.10.x) since master builds upon 0.8.x and no 0.9.x.</p><h4>Routes</h4><p>I wanted to use a subdomain for the api to use the speed of dns to resolve calls to the API versus a page request when we add those features in later.</p><p>To do so I setup a constraint in the routes file for the subdomain <em>api</em> and a namespace for <em>v1</em> to match it to our API controllers (covered in the article above).</p><pre>constraints subdomain: &#39;api&#39; do <br>  namespace :v1 do resources :sessions, only: [:create] <br>  # omitted for brevity <br>  end <br>end</pre><h3>Wrap Up</h3><p>There are a lot of other items I chose not to cover here. I wanted to keep this digestable and cover only the main items to consider when migrating from ASP.NET with SQL Server to Ruby on Rails. However, I am happy to answer questions you may have. If you feel like something crucial is missing from this post, <a href="http://www.chadwilken.com/contact">let me know</a>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=4fecb8d87026" width="1" height="1" alt=""><hr><p><a href="https://medium.com/companydev/the-great-shift-asp-net-to-rails-4fecb8d87026">The Great Shift — ASP.NET to Rails</a> was originally published in <a href="https://medium.com/companydev">CompanyDev</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>