<?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 Michal Korzawski on Medium]]></title>
        <description><![CDATA[Stories by Michal Korzawski on Medium]]></description>
        <link>https://medium.com/@michalkorzawski?source=rss-53cd6986120c------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*AFXol8Yh-UT6nrX8gyxScw.jpeg</url>
            <title>Stories by Michal Korzawski on Medium</title>
            <link>https://medium.com/@michalkorzawski?source=rss-53cd6986120c------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sun, 29 Nov 2026 22:22:48 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@michalkorzawski/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[Why we use Ruby on Rails and (probably) why you should too]]></title>
            <link>https://medium.com/expsoftwareengineering/why-we-use-ruby-on-rails-and-probably-why-you-should-too-59e47460c6d1?source=rss-53cd6986120c------2</link>
            <guid isPermaLink="false">https://medium.com/p/59e47460c6d1</guid>
            <category><![CDATA[software-engineering]]></category>
            <category><![CDATA[ruby-on-rails]]></category>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[ruby-on-rails-development]]></category>
            <category><![CDATA[ruby]]></category>
            <dc:creator><![CDATA[Michal Korzawski]]></dc:creator>
            <pubDate>Thu, 17 Oct 2024 14:00:19 GMT</pubDate>
            <atom:updated>2024-10-17T14:00:19.639Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*qk45yICG8TBfym2WGT-hSw.png" /></figure><p>Let’s get one thing straight. Ruby on Rails might not be the best choice if you’re dealing with Google or Facebook-sized applications. However, if your challenges fall within the small to GitHub-scale range, Rails will serve you just fine.</p><p>My team at eXp-Realty initially had just two developers. Despite that, a small team of two managed to create and actively maintain around <strong>ten</strong> projects. Fast forward to today — we’ve grown to six developers. Over time, the projects we maintain have also grown, and while some were abandoned, new ones were also built. We continue to deliver value for stakeholders at break-neck speeds, addressing pain points effectively, and helping the business grow. Simultaneously, we’re constantly refactoring and upgrading our apps to minimize technical debt and stay on the cutting edge.</p><p>How are we able to do this? The answer is <strong>Ruby on Rails</strong>.</p><p>It’s 2024 — does Rails need an introduction? Created in 2004, it’s a battle-tested framework built on the Ruby language. It has matured over the years to become the go-to tool for many developers and industries worldwide. It’s a startup’s Swiss-army knife.</p><p>But what makes it so effective and capable of accomplishing what we mentioned above?</p><p>Ruby is simple, a user-friendly language that is easy to understand. Even those unfamiliar with it can tell what’s happening in a method because of its human-like syntax.</p><pre># Defining strings<br>greeting = &quot;Hello&quot;<br>name = &quot;Ben&quot;<br><br># Concatenation<br>message = greeting + &quot;, &quot; + name + &quot;!&quot;<br>puts message  # Output: Hello, Ben!<br><br># Interpolation<br>message = &quot;#{greeting}, #{name}!&quot;<br>puts message  # Output: Hello, Ben!<br><br># Changing case<br>puts greeting.upcase     # Output: HELLO<br>puts name.downcase       # Output: ben<br>puts name.capitalize     # Output: Ben<br><br># Splitting the string into an array<br>array = message.split(&#39;,&#39;)<br>puts array.inspect # Output: [&quot;Hello&quot;, &quot; Ben!&quot;]</pre><p>Secondly, Ruby on Rails was created to provide an answer to a specific question: <strong>How do we quickly build a robust web application?</strong> Its inception solved that problem and resulted in a great tool for web developers. It’s impossible not to mention the community around Rails as well — all the passionate people who contribute tools, add features, write documentation, and fix bugs. Personally, it’s comforting to know that when I use Rails, hundreds of brilliant coders have worked hard to cover every edge case; they’re a continuous tide that improves the framework’s developer experience, security, and performance.</p><p>How can I not mention Ruby Gems when trying to convert more of you to the Rails religion? Gems allow you to quickly plug in code from other developers to enhance your application with pre-built features, from UI/UX to authentication and authorization. This is another reason for Rails’ uncanny ability to supercharge development speed.</p><p>Thanks to Ruby on Rails’ famous philosophy — <em>convention over configuration</em> and the ‘Rails way’ — it’s painless to jump into any existing Rails project. No matter the codebase, you know what to expect and where to find everything. The structure is consistent, its patterns prevalent. Due to <a href="https://www.codecademy.com/article/mvc">MVC</a>, finding models, checking routes, inspecting controllers is a breeze. Everything is in its place.</p><p>Recently, the Rails community has officially embraced <a href="https://www.docker.com/">Docker</a>, which makes local development and releases even easier.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/616/1*zhD2QzmHk1k9U0Deo20wDA.png" /><figcaption>Ruby on Rails project structure</figcaption></figure><p>You might think this means Rails is a closed ecosystem. Nothing could be further from the truth, and this point outlines another positive. It’s actually very flexible and open. You can easily incorporate different ideas and technologies — whether it’s Kafka, RabbitMQ, GraphQL, Elasticsearch, or MongoDB. All of these solutions and more are welcome. Rails makes it easy to add services like this if they’re needed to solve the problem you’re facing.</p><p>Finally, I’ll mention one last thing. Building applications with Ruby on Rails is free. While this might seem like an obvious point, it’s still worth mentioning due to the rise of expensive low/no-code alternatives. Think about how much money your company can save on this alone.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=59e47460c6d1" width="1" height="1" alt=""><hr><p><a href="https://medium.com/expsoftwareengineering/why-we-use-ruby-on-rails-and-probably-why-you-should-too-59e47460c6d1">Why we use Ruby on Rails and (probably) why you should too</a> was originally published in <a href="https://medium.com/expsoftwareengineering">eXpSoftwareEngineering</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How to test Jenkins locally]]></title>
            <link>https://medium.com/expsoftwareengineering/how-to-test-jenkins-locally-e1cfc530bca6?source=rss-53cd6986120c------2</link>
            <guid isPermaLink="false">https://medium.com/p/e1cfc530bca6</guid>
            <category><![CDATA[software-engineering]]></category>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[jenkins]]></category>
            <dc:creator><![CDATA[Michal Korzawski]]></dc:creator>
            <pubDate>Fri, 03 Feb 2023 16:39:15 GMT</pubDate>
            <atom:updated>2023-02-03T16:39:15.628Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*DzbuWXg78Ww4bA99UOjMxw.png" /></figure><p>We use Jenkins in every one of our projects. It’s a reliable tool that just works. Recently, the need to test a new change in our <a href="https://www.jenkins.io/doc/book/pipeline/jenkinsfile/">Jenkinsfile</a> emerged; however, there was no way to confidently conclude this would work without testing it locally. So we needed to setup Jenkins and its pipelines locally. This is how I did it.</p><p>Let’s start with setting up Jenkins itself locally. I used <a href="https://hub.docker.com/r/jenkins/jenkins">Jenkins docker image</a> and docker-compose. I believe this to be the easiest and most convenient way to run Jenkins.</p><blockquote><em>This setup is only for local testing. Be aware that in this approach best practices were sacrificed for the sake of ease of use. Please do not use this solution in any environment other than local.</em></blockquote><p>Create a directory like jenkins_local and add a docker-compose.yml file inside. The bare minimum for Jenkins inside a docker-compose.yml should look like this:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/56cac9229e618e953e1615fb63bf4dca/href">https://medium.com/media/56cac9229e618e953e1615fb63bf4dca/href</a></iframe><p>Here we specified ajenkins service that uses jenkins/jenkins:jdk11 image, exposes port 8080 for it, and mounts it to jenkins_home volume.</p><p>Now run docker-compose up to spin up the container. Check the logs and look for the password Jenkins spits out for us during the initial setup. Copy it.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*oyiUf6wWmizanKMaTauwmA.png" /></figure><p>On your browser navigate to <a href="http://localhost:8080/">http://localhost:8080/</a>. On the first run, you should be presented with the Jenkins’s <em>Getting Started </em>page, where you must paste the administrator password copied in the previous step.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Vv38I8Xn4MfvXQz2JBHekw.png" /></figure><p>Next, you can install suggested plugins or select your own.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*TB8TiOt7-aXqfskOP3mMlA.png" /></figure><p>Now is the time for a cup of tea while Jenkins installs all its necessary dependencies. Once that process is finished, you can fill in the form in order to create the first admin user.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Ty7-hnn2fv85caVZb8sB_g.png" /></figure><p>On the next form, it will ask you to set Jenkins URL. We can go with the default <a href="http://localhost:8080/">http://localhost:8080/</a>. Jenkins is now ready to use!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*XUX7CYC43QmOx-vobeu4Vg.png" /></figure><p>Let’s set up a pipeline now that we have Jenkins up and running locally. In the top left corner click “New Item”. Enter a pipeline name, choose <strong>Pipeline</strong> from the list below, and hit <strong>Ok</strong>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*M56cWgPtcql5Gi5cWburig.png" /></figure><p>Next you will see the pipeline configuration form. The most important setting here is where Jenkins can find the pipeline script. Choose <em>Pipeline script from SCM</em> for the <strong>Definition</strong> and <em>Git</em> for <strong>SCM</strong>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*kag9TijetSWPgfPImU5PXg.png" /></figure><p>For <strong>Repository URL,</strong> we don’t want to use a remote repository URL such as a link to a GitHub repo. The intention here is to keep it local. To do that, we want to mount our dockerized application’s project directory — which we’re testing Jenkins locally with — to our Jenkins instance. If your directory structure looks like this —</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/721/1*910vzh5MubBw7v8vSRi4dg.png" /></figure><p>— add ../your_app:/var/jenkins_home/your_app:ro to the local_jenkins docker-compose.yml file. Doing this gives Jenkins access to our application files, including Jenkinsfile. “<em>ro</em>” is a read-only flag so Jenkins won’t be able to override any file or add something we don’t want. Also, we need to add a configuration env <em>hudson.plugins.git.GitSCM.ALLOW_LOCAL_CHECKOUT=true </em>to tell Jenkins that using a local file is permitted.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/fe8f6bfa32ba747126da00e71984e4a8/href">https://medium.com/media/fe8f6bfa32ba747126da00e71984e4a8/href</a></iframe><p>Going back to the <strong>Repository URL, </strong>now instead of a remote repository URL, you can use a local file path: <em>file:////var/jenkins_home/your_app/.git.</em></p><p>Then set up the branch you want Jenkins to build. Leave <strong>Script Path </strong>with default value — Jenkinsfile. Save the configuration.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*pGE_CUhRVSqGF02axqVBDw.png" /></figure><p>If you see this error —</p><blockquote><em>An internal error occurred during form field validation (HTTP 403). Please reload the page and if the problem persists, ask the administrator for help.</em></blockquote><p>— just run docker-compose down and docker-compose up.</p><p>This should be enough for the very basic build flow. Go to Jenkins, click on your pipeline, and then select <em>Build Now</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/683/1*QJ6bnBNEA176h2TdqtaBRQ.png" /></figure><p>You should see your builds now on your pipeline details page.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*tb4PoVwZW-0Bzg13tZiT_w.png" /></figure><p>Keep in mind that its not enough to save changes in Jenkinsfile, you need to use git and commit them; though, actually pushing them isn’t required. Another thing to remember is to be checked out on the branch you specified during the pipeline configuration.</p><p>If you want to trigger a build using a post call to Jenkins, set up a build trigger in your pipeline configuration file. To do this, choose <strong><em>Trigger builds remotely (e.g., from scripts)</em></strong><em>. </em>This<em> </em>allows you to trigger a build by making a post request to a Jenkins pipeline you want to build (more on this later). Also, you need to set up an <em>Authentication Token</em> to be used when making a request. Since we’re using it solely locally, a token as simple as token is suitable. Though for any other environment, make it as long and random as possible.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*f6kBzR8E8zmJree1T9-tPA.png" /></figure><p>At this point, we need to add yet another configuration env to our Jenkins’s docker-compose.yml file. Like with many other settings, CSRF protection can be skipped locally, but that’s not so in other environments.</p><p>hudson.security.csrf.GlobalCrumbIssuerConfiguration.DISABLE_CSRF_PROTECTION=true</p><p>Now our Jenkins docker-compose.yml file should look like this:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/49ac46ecd7d4317342a6e1ff235c4441/href">https://medium.com/media/49ac46ecd7d4317342a6e1ff235c4441/href</a></iframe><p>A user must be created first before triggering a build. In Jenkins, go to <strong>Manage Jenkins &gt; Manage Users</strong> and click <strong>Create User</strong>. Fill in the fields — while noting the username and password — and click <strong>Create User</strong>. This newly created user needs some privileges, so go to <strong>Manage Jenkins &gt; Configure Global Security.</strong></p><p>Under <em>Authorization</em>, choose <strong>Matrix-based security</strong>, then click <strong>Add user</strong>; in the popup, enter the username of the user you just created and select <strong>Ok</strong>. Then check <strong>overall:read</strong>, <strong>job:build</strong>, <strong>job:read</strong> for this user like so —</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*sMUU6Na2FBf9gYBujDhJRQ.png" /></figure><p>— and save the configuration.</p><p>Make sure you have Jenkinsfile in the same directory as your_app , go to the terminal, and run:</p><pre>curl -XPOST -u user_username:user_password http://localhost:8080/job/your_pipeline_name/build?token=your_token</pre><p>Your curl command should look something like this:</p><pre>curl -XPOST -u jenkins:jenkins http://localhost:8080/job/test_pipeline/build?token=token</pre><p>If you’re looking to trigger a build after every commit, add a post-commit file to .git/hooks in your application directory and add a bash script there.</p><pre>#!/bin/bash<br><br>BRANCH=&quot;$(git rev-parse --abbrev-ref HEAD)&quot;<br>if [[ &quot;$BRANCH&quot; == &quot;jenkins_test&quot; ]]; then<br>        curl -XPOST -u jenkins:jenkins http://localhost:8080/job/test_pipeline/build?token=token<br>fi</pre><p>In this example, it will only work on a specific branch — jenkins_test.This can be any branch you want. To make sure the script is executable:</p><pre>chmod +x .git/hooks/post-commit</pre><p>Now the Jenkins pipeline build will trigger every time a commit is made to the jenkins_test branch.</p><p>Thank you for reading, please follow, and feel free to add any suggestions!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e1cfc530bca6" width="1" height="1" alt=""><hr><p><a href="https://medium.com/expsoftwareengineering/how-to-test-jenkins-locally-e1cfc530bca6">How to test Jenkins locally</a> was originally published in <a href="https://medium.com/expsoftwareengineering">eXpSoftwareEngineering</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Deploying Ruby on Rails with AnyCable using Docker & ECS]]></title>
            <link>https://medium.com/expsoftwareengineering/deploying-ruby-on-rails-with-anycable-using-docker-ecs-80f0da2051ba?source=rss-53cd6986120c------2</link>
            <guid isPermaLink="false">https://medium.com/p/80f0da2051ba</guid>
            <category><![CDATA[ruby]]></category>
            <category><![CDATA[anycable]]></category>
            <category><![CDATA[ruby-on-rails]]></category>
            <category><![CDATA[docker]]></category>
            <category><![CDATA[aws]]></category>
            <dc:creator><![CDATA[Michal Korzawski]]></dc:creator>
            <pubDate>Tue, 17 Jan 2023 21:53:40 GMT</pubDate>
            <atom:updated>2023-01-17T21:53:40.590Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*b0F-HpW8usziViJocuEtOw.png" /></figure><p>This is a guide for setting up AnyCable locally using Docker Compose, and deploying it on Amazon Web Services (AWS) Elastic Container Service (ECS). The purpose of this article is not to explain what AnyCable is, so if this is the first time hearing about this awesome Ruby gem, I recommend checking out the <a href="https://docs.anycable.io/architecture">AnyCable documentation website</a>.</p><p>I’m using Rails 7, Ruby 3.1.1. and Redis 4 gem in this application.</p><p>The following steps outline how to setup AnyCable in Docker-Compose:</p><ol><li>Add gem &#39;anycable-rails&#39;, &#39;~&gt; 1.3&#39;, &#39;&gt;=1.3.4&#39; to your Gemfile and run bundle install.</li><li>Run bundle exec rails g anycable:setup</li><li>Ensure your config/cable.yml file looks similar to this:</li></ol><pre># config/cable.yml<br>development:<br>  adapter: &lt;%= ENV.fetch(&quot;ACTION_CABLE_ADAPTER&quot;, &quot;any_cable&quot;) %&gt;<br><br>test:<br>  adapter: test<br><br>production:<br>  adapter: &lt;%= ENV.fetch(&quot;ACTION_CABLE_ADAPTER&quot;, &quot;any_cable&quot;) %&gt;</pre><p>4. Add the config below to config/environments/development.rb and production.rb located in the same folder directory.</p><pre>config.after_initialize do<br>  config.action_cable.url = ActionCable.server.config.url = ENV.fetch(&quot;CABLE_URL&quot;, &quot;ws://localhost:8085/cable&quot;) if AnyCable::Rails.enabled?<br>end</pre><p>5. If you are using cookie-based authentication, make sure your <a href="https://docs.anycable.io/troubleshooting?id=my-websocket-connection-fails-with-quotauth-failedquot-error">cookies are accessible from both the HTTP server and WebSocket server domain</a>:</p><pre>  config.cache_store = :redis_cache_store, {driver: :hiredis, url: ENV.fetch(&#39;REDIS_URL&#39;, &#39;redis://redis:6379&#39;)}<br>  config.session_store :cache_store,<br>    key: &quot;_session&quot;,<br>    domain: :all,<br>    compress: true,<br>    pool_size: ENV.fetch(&quot;REDIS_CONNECTION_POOL_SIZE&quot;, 5).to_i,<br>    expire_after: 1.year</pre><p>6. Create websocket and anycable services in docker-compose.yml</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/238f950072cb7ce9f7ca3b310f4d5dbd/href">https://medium.com/media/238f950072cb7ce9f7ca3b310f4d5dbd/href</a></iframe><p>We’ve already done enough to actually run AnyCable locally using docker-compose. Go ahead and give it a try, docker-compose up and check out the logs. They should be similar to below:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*rO9oCzdp6g1vjRyHYN7JyQ.png" /><figcaption>docker-compose websocker service logs</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*gGoSn_PQIrejt2uxKZ2Bbw.png" /><figcaption>docker compose anycable service logs</figcaption></figure><p>However, actually deploying AnyCable is a slightly different story, and we had much more of a struggle, or fun depending on your point of view. We deployed it to AWS ECS.</p><p>I’d like to give a huge shout-out to <a href="https://www.linkedin.com/in/connor-reid-6572b235">Connor Reid</a> and Joshua Christensen, the two eXp-Realty DevOps geniuses I am blessed to work with. They invented the architecture I’m about to present, and below is a diagram illustrating the solution we ended up implementing.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*2UyH4ow9oN8OlAQdJc4_Yw.png" /></figure><p>For the sake of clarity, I skipped some AWS services here, like VPC, subnets, availability zones, etc..</p><p>It starts with a client hitting either our Rails’ apps’ endpoint or a Websocket service endpoint (specified in CABLE_URL ENV). An Application Load Balancer listener is set up in order to forward HTTPS requests to our Rails app and websocket requests to a <a href="https://github.com/anycable/anycable-go">websocket service</a>. A <em>Websocket service</em> is just an <a href="https://hub.docker.com/r/anycable/anycable-go">official AnyCable-go docker image</a> packed in a container.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/c9e42b6625a04ca9cf398207e75ce55c/href">https://medium.com/media/c9e42b6625a04ca9cf398207e75ce55c/href</a></iframe><p>The Websocket Service needs to communicate with the AnyCable Service. Due to encountering similar issues when setting up the Application Load Balancer — as described in this <a href="https://jetrockets.com/blog/scaling-rails-docker-aws-beanstalk">blog post</a> — we also switched to a Network Load Balancer. Unlike an Application Load Balancer, which works on Layer 7 of OSI model (Application Layer), a Network Load Balancer works on Layer 4 (Transport Layer). It is not familiar with the concept of HTTP; listener options are limited to only TCP, TCP_UDP, TLS, and UDP.</p><p>We set it to listen on TCP port 50051 and forward traffic to the RPC service target group. Adding a health check here was as simple as specifying the protocol and port on which the load balancer will send requests. It’ll check if the service responds.</p><p>One last piece was to create a private hosted zone on Route 53 and set an alias to point to our Network Load Balancer. We saved the private hosted zone domain name as an ENV ANYCABLE_RPC_HOST in the WebSocket service.</p><p>Given that all your services’ security groups are set up to allow traffic from each other (such as RDS and ElastiCache to allow inbound traffic from AnyCable), it all should work. Is there something you would do differently, have a suggestion, question or point of clarity? Please let us know in the comments!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=80f0da2051ba" width="1" height="1" alt=""><hr><p><a href="https://medium.com/expsoftwareengineering/deploying-ruby-on-rails-with-anycable-using-docker-ecs-80f0da2051ba">Deploying Ruby on Rails with AnyCable using Docker &amp; ECS</a> was originally published in <a href="https://medium.com/expsoftwareengineering">eXpSoftwareEngineering</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Converting HEIC Images in Ruby on Rails]]></title>
            <link>https://medium.com/expsoftwareengineering/converting-heic-images-in-ruby-on-rails-59242b16be7a?source=rss-53cd6986120c------2</link>
            <guid isPermaLink="false">https://medium.com/p/59242b16be7a</guid>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[software-engineering]]></category>
            <category><![CDATA[ruby-on-rails]]></category>
            <category><![CDATA[heic]]></category>
            <dc:creator><![CDATA[Michal Korzawski]]></dc:creator>
            <pubDate>Fri, 30 Dec 2022 17:20:36 GMT</pubDate>
            <atom:updated>2022-12-30T17:20:36.155Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*lTNe3k7_RS3038MA_ZHUBw.png" /><figcaption>eXp Realty Software Engineering Blog</figcaption></figure><p><em>How to convert High Efficiency Image File Format (.HEIF / .HEIC) images in Ruby on Rails without a library dependency.</em></p><p>Apple’s iOS 11 brought the new HEIC image format into the mainstream. The purpose of HEIC was to save storage space but still provide high fidelity images. However, like many of Apple’s decisions, the arrival of this image format causes a plethora of issues. Now, even unwittingly, many iPhone users are snapping photos solely as HEIC, as opposed to the much more ubiquitous — and supported — JPEG format. The largest consequence of a new-ish image format is the lack of <a href="https://caniuse.com/?search=heic">browser support.</a> Apple’s own Safari browser doesn’t even support them; in fact, not a single browser supports HEIC images.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*iAcWixLtQ2jLZbglSPm1Xg.png" /><figcaption>Caniuse browser support report for HEIC images</figcaption></figure><p>For one of our apps, users upload images often directly from their phone, and often these images are in HEIC format due to the popularity of iPhones. Nearly daily we’d be flooded with errors when these uploads were added, and no amount of UX/UI ever prevented these users from not choosing to upload them. Occasionally, they’d even resort to adding “.jpg” at the end of a HEIC file just to pass validations.</p><blockquote><em>For uploading, we are using Active Storage, and the app is deployed to AWS ECS.</em></blockquote><p>To address this issue and add support of HEIC image uploading, I at first followed a solution from a <a href="https://sipsandbits.com/2022/02/01/support-heic-images-in-a-rails-app-p1/">blog article</a>. <a href="https://sipsandbits.com/author/salomon/">Salomón Charabati</a>’s method worked perfectly well. However, it was quite slow — too slow for us — especially when attaching large HEIC files. Also, one app in particular, requires a minimum of 12 images, where 20 or more is the norm. The Achilles heel of this implementation was the <a href="https://github.com/alexcorvi/heic2any">Heic2any</a> library, which was used for the HEIC images to be previewed on the front end. So after all of this, I came up with my own solution. Let’s start with the backend.</p><p>First, make sure you have gem &quot;image_processing” added to your project’s Gemfile. The image_processing gem makes it easy to work with both ImageMagic and libvips libraries.</p><p>First we need to create an ImageConverter service, which will encapsulate image resizing and image conversion logic.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/eb8fad3ea4ef404d8920ce13918dbe5a/href">https://medium.com/media/eb8fad3ea4ef404d8920ce13918dbe5a/href</a></iframe><p>The two methods — resize_to_limit and convert — are just two of many handy methods from the image_processing gem. Check out <a href="https://github.com/janko/image_processing/">the gem docs</a> to see them all.</p><p>The next step might be considered a little controversial. At first, I wanted to keep this logic closer to <a href="https://api.rubyonrails.org/classes/ActiveStorage/Blob.html">ActiveStorage::Blob</a>. I was experimenting with custom callbacks but was not too fond of them. Any logic I injected into Blob felt too late in the process. This too little too late feeling forced me to take a step back and modify the image parameters before they were ever sent to ActiveStorage::Blob.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/b004f72d2452b36a4b0d9d7cad7e4e9a/href">https://medium.com/media/b004f72d2452b36a4b0d9d7cad7e4e9a/href</a></iframe><p>We map through :images if it’s present in the params and pass them one by one to ImageConverter. ImageConverterwill convert the image to jpg format, and if the image width is larger than 1200, it will also resize it. This service will then return a tempfile which we then pass to ActionDispatch::Http::UploadedFile. From there, we merge the converted images into permitted params.</p><p>So what exactly is <a href="https://api.rubyonrails.org/v6.0.5/classes/ActionDispatch/Http/UploadedFile.html">ActionDispatch::Http::UploadFile</a> anyhow? When we submit a file through an HTML form, multipart/form-data is used to send file content in the request body. <a href="https://github.com/rack/rack">Rack</a> — a middleware between our web application and web server, Puma for example — parses the multipart/form-data parameters into a hash object which looks like:</p><pre>{<br>  &quot;_method&quot;=&gt;&quot;put&quot;,<br>  &quot;property&quot;=&gt;<br>    {&quot;images&quot;=&gt;<br>      [{:filename=&gt;&quot;IMG_6542 (1).HEIC&quot;,<br>        :type=&gt;&quot;image/heif&quot;,<br>        :name=&gt;&quot;property[images][]&quot;,<br>        :tempfile=&gt;#&lt;File:/tmp/RackMultipart20221128-1-1no4h17.HEIC&gt;,<br>        :head=&gt;&quot;Content-Disposition: form-data; name=\&quot;property[images][]\&quot;; filename=\&quot;IMG_6542 (1).HEIC\&quot;\r\nContent-Type: image/heif\r\n&quot;}<br>      ],<br>     },<br>}</pre><p><a href="https://api.rubyonrails.org/v6.0.5/classes/ActionDispatch/Http/UploadedFile.html">ActionDispatch::Http::UploadFile</a> is used to wrap a file’s params passed to Rails by <a href="https://github.com/rack/rack">Rack</a> as a hash. It also adds a few methods along the way.</p><p>For the frontend, we want to make a HEIC image previewer, but without using the Heic2any library, which we already covered was too slow for us.</p><p>The steps are pretty simple. We grab a file and wrap it in a FormData object. Next, we use fetch to make an asynchronous post request to ImageController#convert_heic method — more about this soon — and read the response using <a href="https://developer.mozilla.org/en-US/docs/Web/API/Response/blob">blob()</a> . This method returns a <a href="https://developer.mozilla.org/en-US/docs/Web/API/Blob">Blob</a> which we put into an object URL using URL.createObjectURL. That object URL is then used as a source for the image tag, which is inserted into the DOM as an HTML img element.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/cae1fdd5b9d97be33c6b4a758495bee5/href">https://medium.com/media/cae1fdd5b9d97be33c6b4a758495bee5/href</a></iframe><p>It’s evident the conversion for the images’ frontend previews are taking place on the backend, so let’s take a peek inside the ImagesController where this is transpiring.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/cc506ae927a3f5ec19628b09cacadcdf/href">https://medium.com/media/cc506ae927a3f5ec19628b09cacadcdf/href</a></iframe><p>We reused the ImageConverter service here; where after converting and resizing, the image is sent back to the client. That’s it!</p><p>I mentioned above that using the Heic2any library was slow. For more evidence, I added a simple comparison of the two below. Thank you so much for reading and click Follow to see more articles!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Av333TLiATemB7iQE7Z6wA.gif" /><figcaption>How the HEIC conversion looks on the front end, and comparison. Left is Heic2any and right is custom solution.</figcaption></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=59242b16be7a" width="1" height="1" alt=""><hr><p><a href="https://medium.com/expsoftwareengineering/converting-heic-images-in-ruby-on-rails-59242b16be7a">Converting HEIC Images in Ruby on Rails</a> was originally published in <a href="https://medium.com/expsoftwareengineering">eXpSoftwareEngineering</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[CableReady and Rails Background Jobs in Views]]></title>
            <link>https://medium.com/expsoftwareengineering/cableready-and-rails-background-jobs-in-views-86074eaac3a3?source=rss-53cd6986120c------2</link>
            <guid isPermaLink="false">https://medium.com/p/86074eaac3a3</guid>
            <category><![CDATA[frontend]]></category>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[backend]]></category>
            <category><![CDATA[cableready]]></category>
            <category><![CDATA[ruby-on-rails]]></category>
            <dc:creator><![CDATA[Michal Korzawski]]></dc:creator>
            <pubDate>Mon, 12 Sep 2022 20:14:26 GMT</pubDate>
            <atom:updated>2022-09-12T20:14:26.575Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*SG60e-l13tpzn1jIoGQEFQ.png" /></figure><p>Using CableReady inside of a Ruby on Rails app to dynamically update the page and view based on a Sidekiq background job’s progress.</p><p>In the world of Web Dev, a common practice, and often preferable approach for handling long-running methods, is to run the intensive action as a background job. It’s a simple and effective solution, but just like everything we web programmers face, there are pros and cons to background jobs. For example, the user won’t receive any feedback generally until this job is finished. For a particular feature I ran into, I needed to display some front-end feedback to the user and to change the page’s content contingent on the progress of this method. One traditional way to do this would be to create a dedicated route and controller#method, while executing Ajax calls every few seconds; however there is an easier way. Considering how much of a Swiss army knife it is, <a href="https://cableready.stimulusreflex.com/">CableReady</a> is a perfect tool for this.</p><p>Before I go any further, let me clarify a bit about what CableReady really is. Here’s a quote from the official website:</p><pre>CableReady is a Ruby gem that was first released in May 2017. It lets you <strong>create great real-time user experiences</strong> by triggering client-side DOM changes, events and notifications over <a href="https://guides.rubyonrails.org/action_cable_overview.html">ActionCable</a> web sockets.</pre><p>Besides the fact that it saves us from having to write too much Javascript in Rails apps 😈, the one aspect of CableReady that completely sold me is below, also from their documentation.</p><pre>Unlike Ajax requests, operations are not always initiated by user activity - or even the user&#39;s browser.</pre><p>What this means is CableReady can be used <a href="https://cableready.stimulusreflex.com/cableready-everywhere">almost everywhere</a>! In this circumstance, we are going to use it inside of a plain old ruby object — <a href="https://steveklabnik.com/writing/the-secret-to-rails-oo-design">PORO</a>.</p><blockquote><em>Before we move on, I’d like to point out some things. CableReady is used together with </em><a href="https://docs.stimulusreflex.com/"><em>StimulusReflex</em></a><em>, or to be more precise, I use StimulusReflex with CableReady since it is a direct dependency. Because of this, CableReady can be called directly inside a Reflex class, without additional configuration. Reflex will take care of the channel CableReady will broadcast to. However, one thing to keep in mind is CableReady will broadcast to the current user when called inside a Reflex.</em></blockquote><p>Let’s start with a CSV importer. A typical CSV importer in Ruby may look very similar to this:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/17801a88e1f85fba5cc959e118f05534/href">https://medium.com/media/17801a88e1f85fba5cc959e118f05534/href</a></iframe><p>Although this works, it’s boring, in the background, and hidden from the user’s view. They have no idea if their importing process is running or where they stand, so let’s show the user its progress in real-time. To start, I’ll include CableReady::Broadcaster in our Importer class.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/0157a7066b7969e31857855866b28e25/href">https://medium.com/media/0157a7066b7969e31857855866b28e25/href</a></iframe><p>Then we need to create an ActionCable Channel class</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/77decab360c4383b3e87f90b25f1d388/href">https://medium.com/media/77decab360c4383b3e87f90b25f1d388/href</a></iframe><p>…and a channel subscriber.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/43eee6e7226256169a9721263fbdc3f4/href">https://medium.com/media/43eee6e7226256169a9721263fbdc3f4/href</a></iframe><p>Now on every page load, a consumer creates a subscription to the UserChannel. After the consumer subscribes to UserChannel, the <em>subscribed</em> method on UserChannel is called. This will use stream_for to subscribe to a broadcast like <em>user:Z2lkOi8vYnJva2VyLXZpc2lvbi9Vc2VyOjpBZG1pbi8x,</em> which is a name generated from the channel name (user) and model instance (GlobalID of a current user). To exemplify this, in the logs we see the following:</p><pre>[ActionCable] UserChannel is transmitting the subscription confirmation<br>[ActionCable] UserChannel is streaming from user:Z2lkOi8vYnJva2VyLXZpc2lvbi9Vc2VyOjpBZG1pbi8x</pre><p>From now on we can use code like this:</p><p>cable_ready[UserChannel].remove(selector: &#39;some_selector&#39;).broadcast_to(current_user)</p><p>… to broadcast to the current user.</p><p>Now that we have CableReady inside our PORO and a channel set up, time to revisit our Importer class; here, we should flesh out the method in order to keep track of how many CSV rows have already been processed.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/db454113a721fdddc891e51b70738753/href">https://medium.com/media/db454113a721fdddc891e51b70738753/href</a></iframe><p>Given that you have a div with the selector id of processed-row-number-container in your view, on each CSV iteration, the number will increment to reflect the counter variable; all being updated in real-time via CableReady and the text_content DOM manipulation (which is quite simply Javascript’s .textContent property).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*hTTF5ZMDjApmOnRV4ZL44g.gif" /></figure><p>As a backend developer, this is good enough for me, and I would leave it as is! 😂 But thankfully, I have a <a href="https://medium.com/@benbroestl">great friend on my team</a> who knows a thing or two about design and implemented it with a nice HTML progress bar.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*6jIVOA9jTJzzrnJcoBmP5Q.gif" /></figure><p>This is a big improvement for the user, but how about we find out what else we can do? Say we want to update the view from a <a href="https://github.com/mperham/sidekiq">Sidekiq</a> job.</p><p>For example, imagine a web app that displays a leaderboard of some sort. In the background, a rake job runs every few minutes that fetches the newest scores. It’s just as easy to update a view from that job using CableReady as well.</p><p>Assuming this leaderboard is accessible by all users, the leaderboard channel may look like this:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/47d4d89ccc04aea466042b69f2def3ed/href">https://medium.com/media/47d4d89ccc04aea466042b69f2def3ed/href</a></iframe><p>Instead of using current_user as we did before, we use a string “scores”. In the logs, it looks radically different from before when we used user:</p><pre>[ActionCable] LeaderboardChannel is transmitting the subscription confirmation<br>[ActionCable] LeaderboardChannel is streaming from leaderboard:scores</pre><p>So before, when broadcasting a message to current_user , it was meant for only one user to see that view, hence the massive string ID from users:user_global_id. In this leaderboard example leaderboard:scores, the broadcast will be published to all logged-in users, which is our goal here.</p><p>Just like before, a channel subscriber needs to be created, and then the only thing left is the job itself.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/bac135b46c7968eaf3be1ed119301d01/href">https://medium.com/media/bac135b46c7968eaf3be1ed119301d01/href</a></iframe><p>With merely a few lines of code, we implemented a background job that will update our view. How cool! And this is just the tip of the iceberg. As demonstrated, you can use CableReady pretty much anywhere, so you are limited only by your creativity. With CableReady, you can add an amazing amount of reactivity to your Rails monolithic app, while maintaining a concise and simple stack.</p><p>Interested in how we at eXp-Realty are embracing the Rails monolith? <a href="https://medium.com/@benbroestl">Benjamin Broestl</a> (author of the aforementioned progress bar) started a<a href="https://medium.com/expsoftwareengineering/a-legacy-rails-apps-journey-into-2022-part-1-view-components-6c1d319513f7"> series of blog posts about it.</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=86074eaac3a3" width="1" height="1" alt=""><hr><p><a href="https://medium.com/expsoftwareengineering/cableready-and-rails-background-jobs-in-views-86074eaac3a3">CableReady and Rails Background Jobs in Views</a> was originally published in <a href="https://medium.com/expsoftwareengineering">eXpSoftwareEngineering</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Rails, Reflex, and Dynamic Filtered Pagination]]></title>
            <link>https://medium.com/expsoftwareengineering/rails-reflex-and-dynamic-filtered-pagination-3d0bce9d860e?source=rss-53cd6986120c------2</link>
            <guid isPermaLink="false">https://medium.com/p/3d0bce9d860e</guid>
            <category><![CDATA[pagination]]></category>
            <category><![CDATA[pagy]]></category>
            <category><![CDATA[stimulusreflex]]></category>
            <category><![CDATA[ruby-on-rails]]></category>
            <category><![CDATA[cableready]]></category>
            <dc:creator><![CDATA[Michal Korzawski]]></dc:creator>
            <pubDate>Mon, 15 Aug 2022 17:42:02 GMT</pubDate>
            <atom:updated>2022-08-15T17:42:02.850Z</atom:updated>
            <content:encoded><![CDATA[<p>Implementing <a href="https://evilmartians.com/chronicles/hotwire-reactive-rails-with-no-javascript">HTML over the wire</a> with combined search, filtered querying pagination via Ruby on Rails and Stimulus Reflex.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*r4k8MejUShjJ_Cq8NaStUA.png" /></figure><p>Pagination is a common feature on web apps and can be found everywhere from your first search on Google to a niche forum. It’s essential for viewing a large amount of data by dividing queried results into more organized and consumable sections, usually in the form of numeric pages.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*P0gxyrX-h7KY_DKoRY14yQ.png" /><figcaption>Google’s pagination</figcaption></figure><p>However, pagination can be difficult to implement, especially when used in conjunction with other features such as search and filters. We also want our users to not have to wait for a page reload and to see their filters dynamically update, just as it would in a SPA. The good news is modern Rails doesn’t need something like React to do this; we don’t even have to venture outside of the Rails monolith!</p><p>We are early adopters of <a href="https://docs.stimulusreflex.com/">Stimulus Reflex </a>and its dependency <a href="https://cableready.stimulusreflex.com/">Cable Ready</a> inside eXp-Realty’s Innovation Hub team. These packages allow real-time, HTML over the wire updates to the DOM. We use some form of pagination in every one of our web apps, and typically this is a variation on infinite scroll; which is a simple approach.</p><p>Recently, there was a request by the product team to replace our good old infinity scroll with numeric based pagination. Seems simple enough, although, there were a few special things to take under consideration:</p><ol><li>Allow search queries — when a user searches for “foo”, we need to paginate through a scoped collection</li><li>On top of a search, support a lot (twelve total) of user dropdown selection and toggle filters.</li><li>It all should work with Stimulus Reflex</li></ol><p>Let’s take a look at the components.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ODIJH9PgxjSfTo26oilCiQ.png" /><figcaption>Search, filters, and pagination view</figcaption></figure><p>The Search bar is an input field with a data-reflex attribute in it. The reflex points to results method in FilterReflex, which will be called on every user’s keyup event.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/d662f8b958f21d7f51f962d8cb37d540/href">https://medium.com/media/d662f8b958f21d7f51f962d8cb37d540/href</a></iframe><p>The filters component is a form and its submit action is intercepted by the FilterReflex#results method.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/a9d30eabf2bca374d1ad3e515470e8e5/href">https://medium.com/media/a9d30eabf2bca374d1ad3e515470e8e5/href</a></iframe><p>Lastly, there is a table displaying a collection of ActiveRecord items. I decided to go with the <a href="https://github.com/ddnexus/pagy">pagy</a> Ruby gem and to abstract all the pagination logic. Pagy was a good choice due to its speed and extensibility.</p><p>Now we have all the pieces ready, so it’s time to assemble them together. Step one is to connect pagy’s pagination logic to Stimulus Reflex.</p><p>Pagy’s default implementation is to add a parameter, like ?page=3 to the url, and each time the pagination’s page numbers are clicked, the page will reload. This is not ideal for that snappy SPA feel we want, and to accomplish that, we shall call a reflex action every time a pagy page is selected.</p><p>Pagy’s navigation helper looks like this &lt;%= pagy_nav(@pagy) %&gt;. You can customize the tags this helper generates by adding the :link_extra attribute. In order to add a data-reflex action, our helper now looks like this:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/de5715bb96b1c3102fcce70f3e12a42b/href">https://medium.com/media/de5715bb96b1c3102fcce70f3e12a42b/href</a></iframe><p>Now every time you click on a pagy page, the FilterReflex#results method will be called. Great! But this is where the good news, and pagy’s magic quickly ends. Because now we have to manually tell pagy which page we want to visit.</p><p>Lets grab the page number first:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/3c8470155f4ceb205f04684076a3a28f/href">https://medium.com/media/3c8470155f4ceb205f04684076a3a28f/href</a></iframe><p>The rest is just standard page table morphs via Stimulus Reflex to update the DOM. Lets add the filters to it. As mentioned and shown above, the filters are merely form fields being submitted to the server, and we can intercept these by using strong parameters inside the reflex.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/5389464d7969d18d5e8866446eb12160/href">https://medium.com/media/5389464d7969d18d5e8866446eb12160/href</a></iframe><p>Submitting filters and handling scoping for Active Record collections on the Reflex side works, but what about when the user clicks to go to page 2? Well, all of those applied filters on the collection will disappear. The reason for that is due to the fact that the filter info isn’t preserved anywhere, so going to a different page will reset whatever had been applied, despite the filter inputs still containing the values in them. In order to fix this short circuit, the filter data needs to be passed to the pagy helper. We do this by passing JSON with params to the collection view morph and modifying the pagy helper. In the FilterReflex#results method, you need to check for params-hash before checking filtered_params.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/4ae604b0386dff0553a5ea71910ab9f9/href">https://medium.com/media/4ae604b0386dff0553a5ea71910ab9f9/href</a></iframe><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/8e6f676ae273e7fdeec9fe5d0d63ad5e/href">https://medium.com/media/8e6f676ae273e7fdeec9fe5d0d63ad5e/href</a></iframe><p>Now the form’s filters will carry over to the new page when a user clicks “page 2”. This gets us to the point of having pagination working with Stimulus Reflex and filters. Search queries are the last piece of the puzzle, and search presents many of the same problems as filters did; data needs to be passed to the pagy helper somehow. The easiest, and most obvious, way would be to include it in the params_hash.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/7d070258ae4e44b2cef06ad25a5c6777/href">https://medium.com/media/7d070258ae4e44b2cef06ad25a5c6777/href</a></iframe><p>This naïve implementation works at first glance, but it has a serious flaw: The user starts to type in the search, deletes it, and goes to page 2. In this scenario, the results scoped by the first letter of the search query will remain. To fix that we need to distinguish when we are calling the FilterReflex#result method via search, and not elsewhere in the filters.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/9ecde7831145656116701721dca8f3fb/href">https://medium.com/media/9ecde7831145656116701721dca8f3fb/href</a></iframe><p>We need to now update query in the results method:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/7ae33af2b0ca05d9b1b3e4cea3e8e748/href">https://medium.com/media/7ae33af2b0ca05d9b1b3e4cea3e8e748/href</a></iframe><p>Okay! This is working as intended with search and pagination simultaneously. However, when throwing filters in with search, all our hard work goes out the window.</p><p>Filters are simply inputs inside of a form, so we can add an additional hidden input there as a placeholder for the query.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/7256b73958e39828e79f10bd417dcdac/href">https://medium.com/media/7256b73958e39828e79f10bd417dcdac/href</a></iframe><p>Then in the FilterReflex#results method we need to morph this field and update it with the search query value.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/cf210cee9419606d3afb66efa42c5ef2/href">https://medium.com/media/cf210cee9419606d3afb66efa42c5ef2/href</a></iframe><p>Almost there! The final order of business is to update the search input field with any data from the form’s filters. This is as easy as passing params_hash to the search input field as a data-attribute.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/9750a55a338c772b0c6ecb7f0a27ae69/href">https://medium.com/media/9750a55a338c772b0c6ecb7f0a27ae69/href</a></iframe><p>That’s it. Now search, filters, and pagination is all connected under one glorious and true Stimulus Reflex method!</p><p>As you can see, it isn’t too easy to create an elegant pagination solution that works well for all users, but I hope you have found this article helpful in any way. Ideally, it may inspire you to create your own pagination solution or use a variation of mine.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=3d0bce9d860e" width="1" height="1" alt=""><hr><p><a href="https://medium.com/expsoftwareengineering/rails-reflex-and-dynamic-filtered-pagination-3d0bce9d860e">Rails, Reflex, and Dynamic Filtered Pagination</a> was originally published in <a href="https://medium.com/expsoftwareengineering">eXpSoftwareEngineering</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>