<?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 Ashwin Borkar on Medium]]></title>
        <description><![CDATA[Stories by Ashwin Borkar on Medium]]></description>
        <link>https://medium.com/@ashwinborkar1997?source=rss-63a18ee16805------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*PFtlb5WBKxLEhOkqYfI7Cg.jpeg</url>
            <title>Stories by Ashwin Borkar on Medium</title>
            <link>https://medium.com/@ashwinborkar1997?source=rss-63a18ee16805------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sun, 22 Nov 2026 16:10:03 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@ashwinborkar1997/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[ Building Real-Time WebSockets in Rails API with ActionCable (Step-by-Step Guide)]]></title>
            <link>https://medium.com/@ashwinborkar1997/building-real-time-websockets-in-rails-api-with-actioncable-step-by-step-guide-710ed0a98dea?source=rss-63a18ee16805------2</link>
            <guid isPermaLink="false">https://medium.com/p/710ed0a98dea</guid>
            <category><![CDATA[websockets-in-rails-api]]></category>
            <dc:creator><![CDATA[Ashwin Borkar]]></dc:creator>
            <pubDate>Fri, 17 Apr 2026 09:51:38 GMT</pubDate>
            <atom:updated>2026-04-17T09:51:38.532Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/900/0*q4eFFvYA6fkYH7UO.png" /></figure><p>Real-time features are no longer a luxury — they’re expected. Whether it’s chat apps, live notifications, or activity feeds, users want updates instantly.</p><p>In this guide, you’ll learn how to implement <strong>WebSockets in a Rails API</strong> using <strong>ActionCable, Redis, and Doorkeeper authentication</strong> — with a clean, production-ready architecture.</p><h3>🔧 Prerequisites</h3><p>Before we start, make sure you have:</p><ul><li>Rails 6+ API application</li><li>Redis installed and running</li><li>Basic understanding of MVC</li><li>Doorkeeper (OAuth) already set up</li></ul><h3>⚡ Step 1: Setup ActionCable</h3><h3>Add required gems</h3><pre># Gemfile<br>gem &#39;redis&#39;, &#39;~&gt; 4.0&#39;<br>gem &#39;actioncable&#39;</pre><pre>bundle install</pre><h3>Configure Redis</h3><p>Create config/cable.yml:</p><pre>development:<br>  adapter: redis<br>  url: &lt;%= ENV.fetch(&quot;REDIS_URL&quot;) %&gt;/2<br>  channel_prefix: development_cable</pre><pre>test:<br>  adapter: redis<br>  url: &lt;%= ENV.fetch(&quot;REDIS_URL&quot;) %&gt;/2<br>  channel_prefix: test_cable</pre><pre>production:<br>  adapter: redis<br>  url: &lt;%= ENV.fetch(&quot;REDIS_URL&quot;) { &quot;redis://localhost:6379&quot; } %&gt;/2<br>  channel_prefix: production_cable</pre><h3>Mount WebSocket endpoint</h3><pre># config/routes.rb<br>mount ActionCable.server =&gt; &#39;/cable&#39;</pre><h3>🔐 Step 2: Authenticate WebSocket Connections</h3><p>Create:</p><pre># app/channels/application_cable/connection.rb<br>module ApplicationCable<br>  class Connection &lt; ActionCable::Connection::Base<br>    identified_by :current_user<br>  def connect<br>        self.current_user = find_verified_user<br>        current_user.presence&amp;.online!<br>        logger.info &quot;WebSocket connected: #{current_user.id}&quot;<br>      rescue =&gt; e<br>        logger.error &quot;Connection failed: #{e.message}&quot;<br>        reject_unauthorized_connection<br>      end<br>      private<br>      def find_verified_user<br>        token = doorkeeper_token<br>        reject_unauthorized_connection unless token&amp;.accessible?<br>        user = User.find_by(id: token.resource_owner_id)<br>        reject_unauthorized_connection unless user<br>        user<br>      end<br>    end<br>end</pre><p>👉 This ensures only authenticated users can connect.</p><h3>📡 Step 3: Create Your First Channel</h3><pre>rails generate channel notifications</pre><pre># app/channels/notifications_channel.rb<br>class NotificationsChannel &lt; ApplicationCable::Channel<br>  def subscribed<br>    return reject unless current_user<br>    stream_from &quot;notifications##{current_user.id}&quot;<br>  end<br>end</pre><p>🎯 Each user now has a personal real-time stream.</p><h3>📢 Step 4: Build a Broadcast Service</h3><pre># app/managers/api/broadcast_to_action.rb<br>module Api<br>  class BroadcastToAction<br>    def initialize(user, type, payload, **options)<br>      @user = user<br>      @type = type<br>      @payload = payload<br>      @options = options.with_indifferent_access<br>    end<br>   def call<br>      stream_key = @options[:stream_key]<br>      data = @options[:data] || {<br>        type: @type,<br>        payload: @payload<br>      }<br>      ActionCable.server.broadcast(<br>        stream_key || &quot;@user.id&quot;&gt;root##{@user.id}&quot;,<br>        data.as_json<br>      )<br>    end<br>  end<br>end</pre><p>💡 This keeps broadcasting logic clean and reusable.</p><h3>💬 Step 5: Build a Real-Time Chat System</h3><pre>rails generate channel conversations</pre><pre># app/channels/conversations_channel.rb<br>class ConversationsChannel &lt; ApplicationCable::Channel<br>  def subscribed<br>    return reject unless current_userconversation = Conversation.find_by(id: params[:conversation_id])<br>    return reject unless conversation<br>    return reject unless authorized?(conversation)<br>    stream_from &quot;conversations##{conversation.id}&quot;<br>    Message.view_all_for(conversation, current_user)<br>    broadcast_conversation_update(conversation)<br>  end<br>  def receive(data)<br>    case data[&quot;event&quot;]<br>    when &quot;typing&quot;<br>      handle_typing_event(data)<br>    when &quot;view_messages&quot;<br>      handle_view_messages_event(data)<br>    end<br>  end<br>  private<br>  def authorized?(conversation)<br>    conversation.client_id == current_user.id ||<br>    conversation.contact_id == current_user.id<br>  end<br>end</pre><p>🔥 Features included:</p><ul><li>Real-time messages</li><li>Typing indicators</li><li>Read receipts</li></ul><h3>🔄 Step 6: Auto Broadcast with Model Callbacks</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/721/1*TpBTJ9avxrENK3HKnLjwSQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/521/1*M81NwssqQwJIyPlLChsvZg.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/717/1*Sc2LA1Pd9ZjIvZEQkZG5_w.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/714/1*BC2aZCwk8zeFWwpWtOBV9g.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*rJH9Tftw6O9Q-d6n786lBg.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*_y06Pv6PVmShqp9z6aCGyw.png" /></figure><h3>Conversation model</h3><pre>after_create_commit :broadcast_new_conversation</pre><h3>Message model</h3><pre>after_create_commit :broadcast_new_message</pre><p>🎯 This ensures updates are pushed automatically without manual triggers.</p><h3>🌐 Step 7: Client-Side Setup</h3><h3>Create WebSocket connection</h3><pre>import Cable from &quot;@rails/actioncable&quot;;</pre><pre>App.cable = Cable.createConsumer(<br>  `ws://${window.location.hostname}:3000/cable?access_token=${getAccessToken()}`<br>);</pre><h3>Subscribe to channel</h3><pre>App.cable.subscriptions.create(<br>  { channel: &quot;NotificationsChannel&quot; },<br>  {<br>    received(data) {<br>      console.log(&quot;Notification:&quot;, data);<br>    }<br>  }<br>);</pre><h3>🧪 Step 8: Testing WebSockets</h3><pre>it &quot;accepts valid connection&quot; do<br>  expect { connection.connect }.not_to raise_error<br>end</pre><pre>it &quot;rejects invalid token&quot; do<br>  expect { connection.connect }.to raise_error<br>end</pre><p>✔️ Always test authentication and connection flow.</p><h3>🚀 Step 9: Production Deployment</h3><h3>Redis config</h3><pre>production:<br>  adapter: redis<br>  url: redis://redis:6379</pre><h3>Nginx WebSocket support</h3><pre>location /cable {<br>  proxy_pass http://your-app;<br>  proxy_http_version 1.1;<br>  proxy_set_header Upgrade $http_upgrade;<br>  proxy_set_header Connection &quot;upgrade&quot;;<br>}</pre><h3>📊 Step 10: Monitoring &amp; Debugging</h3><p>Use Redis tools:</p><pre>redis-cli monitor<br>redis-cli info memory</pre><p>Add logs inside channels:</p><pre>Rails.logger.info &quot;User connected&quot;</pre><h3>⚠️ Common Issues</h3><p><strong>401 Unauthorized</strong><br>→ Check token in WebSocket URL</p><p><strong>Messages not received</strong><br>→ Stream name mismatch</p><p><strong>High memory usage</strong><br>→ Optimize Redis + cleanup connections</p><h3>💡 Best Practices</h3><ul><li>Always validate permissions</li><li>Use serializers for consistency</li><li>Add proper logging</li><li>Monitor Redis performance</li><li>Handle disconnections gracefully</li><li>Implement rate limiting</li><li>Use heartbeat/ping system</li></ul><h3>🎯 Final Thoughts</h3><p>You now have a <strong>production-ready real-time system</strong> in Rails using:</p><p>✅ ActionCable<br>✅ Redis<br>✅ Doorkeeper authentication</p><p>This setup enables:</p><ul><li>Live chat</li><li>Notifications</li><li>Presence tracking</li><li>Typing indicators</li></ul><h3>✨ Author</h3><p><strong>Ashwin Borkar</strong></p><p>If you’re building modern apps, real-time isn’t optional anymore — it’s the baseline. Start small, scale smart, and monitor everything.</p><p>Happy coding 🚀</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=710ed0a98dea" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Add a target blank to link in rich text with ruby on rails]]></title>
            <link>https://medium.com/@ashwinborkar1997/add-a-target-blank-to-link-in-rich-text-with-ruby-on-rails-77ecdd55ff01?source=rss-63a18ee16805------2</link>
            <guid isPermaLink="false">https://medium.com/p/77ecdd55ff01</guid>
            <dc:creator><![CDATA[Ashwin Borkar]]></dc:creator>
            <pubDate>Thu, 30 Jan 2025 12:12:05 GMT</pubDate>
            <atom:updated>2025-01-30T12:12:05.223Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*HZHi8UR_fD-1SaAw" /></figure><p>When a user click on a link present in a rich_text it does not open in a new page… It is something very annoying for some of our users at <a href="https://www.komin.io/">Komin.io</a>. We build a LMS and we are leveraging a lot of the RichText / Trix editor features. Unfortunately it is not a default in Rails and not present in the documentation either. The solution implemented has been inspired by this issue: <a href="https://github.com/basecamp/trix/issues/55">https://github.com/basecamp/trix/issues/55</a></p><p>At Komin.io we have a lot of models that has_rich_text :something. Some requirements</p><ul><li>The name of the attribute is not always the same (:body, :text, :comment_body….)</li><li>Sometimes we have many different rich_text elements for a single class…</li><li>For one specific model we don’t the target blank</li></ul><p>We created a concern:</p><pre># app/models/concerns/rich_text_target_blank.rb<br>module RichTextTargetBlank<br>  extend ActiveSupport::Concern</pre><pre>  class_methods do<br>    # Override has_rich_text to include target=&quot;_blank&quot;functionality<br>    def has_rich_text(name)<br>      super(name) # Call the original has_rich_text to set up the rich text association</pre><pre>      # Define the before_save callback to modify the links<br>      before_save do<br>        rich_text_attribute = self.send(name)<br>        if rich_text_attribute.present?<br>          doc = Nokogiri::HTML::DocumentFragment.parse(rich_text_attribute.body.to_html)<br>          doc.css(&#39;a&#39;).each { |a| a[&#39;target&#39;] = &#39;_blank&#39; }<br>          rich_text_attribute.body = doc.to_html<br>        end<br>      end<br>    end<br>  end<br>end</pre><p>The concept is to override the has_rich_text method to add a `before_save` callback.</p><p>In the callback we parse with Nokogori all the `&lt;a&gt;`html tags and add the attribute target=”_blank” on it.</p><p>Then we simple have to include the concern inside our class.</p><pre>class Comment &lt; ApplicationRecord<br>  include RichTextTargetBlank<br>  has_rich_text :body<br>end</pre><p>The last thing to do if you want to modify the existing RichText attachments that you may have in production is to call .save on all the instances.</p><pre>Comment.all.map(&amp;:save)</pre><p>We could also had a no follow attribute but not required in our case because our pages are not indexed by the browsers.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=77ecdd55ff01" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Cocoon gem How to use and why use this in rails .]]></title>
            <link>https://medium.com/@ashwinborkar1997/cocoon-gem-how-to-use-and-why-use-this-in-rails-a0679d74f351?source=rss-63a18ee16805------2</link>
            <guid isPermaLink="false">https://medium.com/p/a0679d74f351</guid>
            <dc:creator><![CDATA[Ashwin Borkar]]></dc:creator>
            <pubDate>Fri, 27 Sep 2024 12:05:30 GMT</pubDate>
            <atom:updated>2024-09-27T12:12:32.676Z</atom:updated>
            <content:encoded><![CDATA[<h3><strong><em>Cocoon gem</em></strong> How to use and why use this in rails .</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/0*I66Cl2a6-Z03K6HS.jpg" /></figure><p>The Cocoon gem in Rails is primarily used to handle <strong>nested forms</strong> with <strong>dynamic associations</strong>. It allows users to dynamically add or remove nested form fields (like adding multiple addresses for a user) without reloading the page. This is useful in situations where an object has many associated objects, and you need to manage these associations dynamically.<br>Why Use Cocoon:</p><ul><li><strong>Dynamic Nested Forms</strong>: Cocoon is perfect for managing nested forms where users can dynamically add or remove fields, which is common in many web applications.</li><li><strong>Simplifies Complex Forms</strong>: If you have associations like has_many or has_and_belongs_to_many, Cocoon simplifies form management for these relationships.</li><li><strong>JavaScript Integration</strong>: It provides JavaScript helpers to add and remove form fields seamlessly, reducing the need to manually write complex JS code.</li></ul><h3>How to Use Cocoon in Rails</h3><h4>1. Add the Gem to Your Gemfile</h4><p>To start, add Cocoon to your Gemfile:</p><pre>gem &#39;cocoon&#39;</pre><p>Then run:</p><pre>bundle install</pre><h4>2. Set Up Associations in Models</h4><p>You need to have nested associations for Cocoon to work effectively.</p><p>For example, if you have a User model that has many addresses:</p><pre># app/models/user.rb<br>class User &lt; ApplicationRecord<br>  has_many :addresses, inverse_of: :user, dependent: :destroy<br>  accepts_nested_attributes_for :addresses, allow_destroy: true<br>end<br><br># app/models/address.rb<br>class Address &lt; ApplicationRecord<br>  belongs_to :user<br>end</pre><h4>3. Create the Form</h4><p>In your form, you’ll need to make use of the fields_for helper to generate nested fields for the associated records. You also need to include the necessary Cocoon hooks.</p><p>For example, in the users form:</p><pre># app/views/users/_form.html.erb<br>&lt;%= form_with(model: @user, local: true) do |f| %&gt;<br>  &lt;%= f.label :name %&gt;<br>  &lt;%= f.text_field :name %&gt;<br>&lt;h3&gt;Addresses&lt;/h3&gt;<br>  <br>  &lt;div id=&quot;addresses&quot;&gt;<br>    &lt;%= f.fields_for :addresses do |address| %&gt;<br>      &lt;%= render &#39;address_fields&#39;, f: address %&gt;<br>    &lt;% end %&gt;<br>  &lt;/div&gt;<br>  <br>  &lt;div&gt;<br>    &lt;%= link_to_add_association &#39;Add Address&#39;, f, :addresses, class: &quot;btn btn-primary&quot; %&gt;<br>  &lt;/div&gt;<br>  <br>  &lt;%= f.submit %&gt;<br>&lt;% end %&gt;</pre><p>The _address_fields partial looks like this:</p><pre># app/views/users/_address_fields.html.erb<br>&lt;div class=&quot;nested-fields&quot;&gt;<br>  &lt;%= f.label :street %&gt;<br>  &lt;%= f.text_field :street %&gt;<br><br>  &lt;%= f.label :city %&gt;<br>  &lt;%= f.text_field :city %&gt;<br><br>  &lt;%= f.label :state %&gt;<br>  &lt;%= f.text_field :state %&gt;<br><br>  &lt;%= link_to_remove_association &quot;Remove Address&quot;, f, class: &quot;btn btn-danger&quot; %&gt;<br>&lt;/div&gt;</pre><h4>4. Include Cocoon’s JavaScript</h4><p>You need to include the Cocoon JavaScript file to make the form fields dynamically addable and removable:</p><p>In your application.js file:</p><pre>//= require cocoon</pre><p>Make sure you’re also including jQuery in your project, as Cocoon relies on it.</p><h4>5. Controller Setup</h4><p>Ensure your strong parameters are set up correctly in the controller to permit nested attributes. For example:</p><pre># app/controllers/users_controller.rb<br>def user_params<br>  params.require(:user).permit(:name, addresses_attributes: [:id, :street, :city, :state, :_destroy])<br>end</pre><p>The _destroy attribute is required to enable removing associated records.</p><h4>6. Use in Views</h4><p>Once set up, users can dynamically add new addresses or remove existing ones in the form without refreshing the page. The form dynamically updates to include these new fields.</p><h3>Why You Should Use Cocoon:</h3><ul><li><strong>Cleaner Code</strong>: Cocoon reduces the need for custom JavaScript or jQuery code to manage dynamic nested forms.</li><li><strong>Easy to Implement</strong>: It’s easy to integrate into Rails applications with a few lines of code.</li><li><strong>Maintainability</strong>: Since it leverages Rails’ fields_for and accepts_nested_attributes_for, it works seamlessly with Rails form helpers.</li></ul><p>Cocoon is ideal for managing dynamic nested forms where you have to deal with multiple associated models, such as adding/removing addresses, phone numbers, or other associated records in forms.</p><p>Thank you</p><p>Ashwin Borkar 😍 💗</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a0679d74f351" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Connection for the FTP and upload file in ftp Using Rails 6.]]></title>
            <link>https://medium.com/@ashwinborkar1997/connection-for-the-ftp-and-upload-file-in-ftp-using-rails-6-763567274fa6?source=rss-63a18ee16805------2</link>
            <guid isPermaLink="false">https://medium.com/p/763567274fa6</guid>
            <dc:creator><![CDATA[Ashwin Borkar]]></dc:creator>
            <pubDate>Fri, 27 Sep 2024 11:59:04 GMT</pubDate>
            <atom:updated>2024-09-27T11:59:04.144Z</atom:updated>
            <content:encoded><![CDATA[<h3>Introduction</h3><p>I broke down the task into the following chunks:</p><ul><li>Connect to SFTP</li><li>Check for a file match(regex came in handy here)</li><li>Download the file into an in-memory storage</li><li>Parse the file data from in-memory into an array</li><li>Destroy the existing locations database (more on this later)</li><li>Iterate through the locations array saving each item as a record</li><li>Reconnect to SFTP and archive the processed file</li></ul><h3>Connecting to SFTP</h3><p><strong>SFTP</strong>, known as <em>SSH File Transfer Protocol</em> or <em>Secure File Transfer Protocol</em> is a secure way of transferring files between two remote systems. The difference between SFTP and FTP (File Transfer Protocol) is that SFTP is a protocol packaged with SSH to transfer data/files over a secure connection.</p><p>To connect to an SFTP server, Ruby has <a href="https://github.com/net-ssh/net-sftp"><strong><em>net-sftp</em></strong></a> and <a href="https://github.com/net-ssh/net-ssh"><strong><em>net-ssh</em></strong></a> gems. Add them to your Gemfile and run bundle install .</p><pre>gem &#39;net-sftp&#39;<br>gem &#39;net-ssh&#39;</pre><p>I had this helper method for starting a standalone SFTP session. It will start up an SSH session using the given arguments, and will then start a new SFTP session with the SSH session. This will block until the new SFTP is fully open and initialized before returning it. Check this <a href="https://www.rubydoc.info/gems/net-sftp/2.0.5/Net/SFTP">documentation</a> for details.</p><pre> def send_file_on_ftp(objc, name)<br>    name = obj.upcase.gsub(&#39;:&#39;,&#39;_&#39;)<br>    error_path = &quot;#{Rails.public_path.join(&quot;night_inventory&quot;)}/#{name}_#{name}_ERROR_OCCURRED_#{Time.zone.now.strftime(&quot;%Y%m%d&quot;)}&quot;<br>    FileUtils.touch(error_path)<br>    options = {<br>      file_path: error_path,<br>      server_name: User.name_ftp.host,<br>      username: User.name_ftp.username,<br>      password: User.name_ftp.password,<br>      port: User.name_ftp.port,<br>      location: User.name_ftp.error_path<br>    }<br>    ftp = FileTransfer::Ftp.new(options).init<br><br>    if ftp.connectable?<br>      if ftp.connected<br>        ftp.obj<br>      else<br>        puts &quot;[FAILED] Unable to Login with FTP&quot;<br>      end<br>    else<br>      puts &quot;[FAILED] FTP Connection Fail&quot;<br>    end<br>    File.delete(error_path)<br>  end</pre><p>after connection automatically call to the Ftp server you can use the <strong>FileZilla.</strong></p><p>thank you <br>Ashwin Borkar</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=763567274fa6" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[how to make your own ruby gem .]]></title>
            <link>https://medium.com/@ashwinborkar1997/how-to-make-your-own-ruby-gem-2c06333b7e6f?source=rss-63a18ee16805------2</link>
            <guid isPermaLink="false">https://medium.com/p/2c06333b7e6f</guid>
            <dc:creator><![CDATA[Ashwin Borkar]]></dc:creator>
            <pubDate>Fri, 03 May 2024 09:17:05 GMT</pubDate>
            <atom:updated>2024-05-03T09:17:05.969Z</atom:updated>
            <content:encoded><![CDATA[<h3>how to make your own ruby gem .</h3><h3>First Homemade Gem — Create and publish a simple Gem</h3><h3>Introduction</h3><p>I learned about Ruby Gem at an in-house study session. As a review, I will write about how to make gems while making them myself. It’s a fairly simple implementation, so I think you can make it in about 30 minutes. *This does not include the time required for advance preparation.</p><p>By the way, this is my environment.</p><pre>Ruby version 2.4.1<br>Bundler version 2.0.2</pre><h3>How to make gems</h3><h3>Advance preparation</h3><p>The following preparations are required in advance.</p><ul><li>Create a new repository on Github to store the source code of the Gem you will create this time</li><li>RubyGems account registration</li><li>Bundler</li><li>If it’s less than bundle -v Bundler version 1.9.0, gem update bundlerplease do so.</li></ul><h3>Create the base of the gem</h3><p>Create it using Bundler. Although it is possible to create gems without Bundler, it seems like using Bundler is the standard now.</p><p>bundle gem gem_nameYou can easily create a gem base.</p><p>HelloWorld would be fine, but this time I’d like to create a Gem that respects a certain famous actor.</p><pre>$ bundle gem xano_api_gem<br><br># Because it is not possible to upload the same gem to RubyGems, please change it.</pre><p>bundle gemIf you are using the command for the first time, you will be asked if you want to write tests in RSpec or minitest, and if you want to create CODE_OF_CONDUCT.md and LICENSE.txt.</p><p>When it comes to whether to write tests in RSpec or minitest, I think you should choose whichever you are more familiar with. I’m choosing RSpec.<br>I think YES is fine for “Can I create CODE_OF_CONDUCT.md and LICENSE.txt?”</p><ul><li>CODE_OF_CONDUCT.md</li><li>Provides a code of conduct that we expect all contributors to the gem to follow.</li><li>LICENSE.txt</li><li>Includes <a href="https://ja.wikipedia.org/wiki/MIT_License">MIT license .</a></li></ul><pre>xano_api_gem/<br>── xano_api/<br>│   ├── client.rb<br>│   ├── error.rb<br>│   └── version.rb<br>├── spec/<br>│   ├── client_spec.rb<br>│   ├── error_spec.rb<br>│   └── ...<br>├── .gitignore<br>├── Gemfile<br>├── LICENSE<br>├── README.md<br>└── xano_api_gem.gemspec</pre><h3>Modify gemspec</h3><p>gem_name.gemspec defines metadata. The parts that need to be rewritten are marked as TODO, so we will correct them. If you don’t fix it, bundle installyou&#39;ll get angry.</p><p><strong>xano_api_gem.gemspec</strong></p><pre># frozen_string_literal: true<br><br>require_relative &quot;lib/xano_api_gem/version&quot;<br><br>Gem::Specification.new do |spec|<br>  spec.name          = &quot;xano_api_gem&quot;<br>  spec.version       = XanoApiGem::VERSION<br>  spec.authors       = [&quot;Ashwin Borkar&quot;]<br>  spec.email         = [&quot;ashwinborkar1997@gmail.com&quot;]<br><br>  spec.summary = &quot;A Ruby gem for interacting with the Xano API.&quot;<br>  spec.description = &quot;A Ruby gem for interacting with the Xano API. Provides a client for making requests to the Xano API and error handling.&quot;<br>  spec.homepage      = &quot;https://github.com/ashwin-borkar/xano_api_gem&quot;<br>  spec.license       = &quot;MIT&quot;<br>  spec.required_ruby_version = Gem::Requirement.new(&quot;&gt;= 2.3.0&quot;)<br><br>  spec.metadata[&quot;allowed_push_host&quot;] = &quot;https://rubygems.org&quot;<br><br>  spec.metadata[&quot;homepage_uri&quot;] = spec.homepage<br>  spec.metadata[&quot;source_code_uri&quot;] = &quot;https://github.com/ashwin-borkar/xano_api_gem&quot;<br>  spec.metadata[&quot;changelog_uri&quot;] = &quot;https://github.com/ashwin-borkar/xano_api_gem&quot;<br><br>  # Specify which files should be added to the gem when it is released.<br>  # The `git ls-files -z` loads the files in the RubyGem that have been added into git.<br>  spec.files = Dir.chdir(File.expand_path(__dir__)) do<br>    `git ls-files -z`.split(&quot;\x0&quot;).reject { |f| f.match(%r{\A(?:test|spec|features)/}) }<br>  end<br>  spec.bindir        = &quot;exe&quot;<br>  spec.executables   = spec.files.grep(%r{\Aexe/}) { |f| File.basename(f) }<br>  spec.require_paths = [&quot;lib&quot;]<br><br>  # Uncomment to register a new dependency of your gem<br>  # spec.add_dependency &quot;example-gem&quot;, &quot;~&gt; 1.0&quot;<br><br>  # For more information and examples about making a new gem, checkout our<br>  # guide at: https://bundler.io/guides/creating_gem.html<br>end</pre><p>Once the modifications are complete, install the dependent gems.</p><pre>bundle install</pre><h3>write the code</h3><p>Let’s write the code in the lib directory!<br>client.rb</p><pre>require &#39;net/http&#39;<br>require &#39;uri&#39;<br>require &#39;json&#39;<br><br>module XanoApiGem<br>  class Client<br>    def initialize(api_key)<br>      @api_key = api_key<br>      @base_url = &#39;https://api.xano.com/v1&#39;  # Base URL for Xano API<br>    end<br>    <br>    def get(endpoint, params = {})<br>      uri = build_uri(endpoint, params)<br>      request = Net::HTTP::Get.new(uri.request_uri)<br>      make_request(request)<br>    end<br>    <br>    def post(endpoint, data)<br>      uri = build_uri(endpoint)<br>      request = Net::HTTP::Post.new(uri.request_uri)<br>      request.body = data.to_json<br>      make_request(request)<br>    end<br>    <br>    def put(endpoint, data)<br>      uri = build_uri(endpoint)<br>      request = Net::HTTP::Put.new(uri.request_uri)<br>      request.body = data.to_json<br>      make_request(request)<br>    end<br>    <br>    def delete(endpoint)<br>      uri = build_uri(endpoint)<br>      request = Net::HTTP::Delete.new(uri.request_uri)<br>      make_request(request)<br>    end<br>    <br>    private<br>    <br>    def build_uri(endpoint, params = {})<br>      uri = URI.parse(&quot;#{@base_url}/#{endpoint}&quot;)<br>      uri.query = URI.encode_www_form(params) unless params.empty?<br>      uri<br>    end<br>    <br>    def make_request(request)<br>      http = Net::HTTP.new(uri.host, uri.port)<br>      http.use_ssl = true<br>      request[&#39;Authorization&#39;] = &quot;Bearer #{@api_key}&quot;<br>      request[&#39;Content-Type&#39;] = &#39;application/json&#39;<br>      <br>      response = http.request(request)<br>      parse_response(response)<br>    end<br>    <br>    def parse_response(response)<br>      case response<br>      when Net::HTTPSuccess<br>        JSON.parse(response.body)<br>      else<br>        raise APIError.new(response.code, response.body)<br>      end<br>    end<br>  end<br>end</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*qgOV3ad2HBiUE5hkIKpXcg.png" /></figure><h3>pload to RubyGems</h3><p>rake releaseIt can be uploaded using command.</p><ul><li>Please register a RubyGems account in advance and create a file from <a href="https://rubygems.org/profile/edit">the profile editing page .</a>~/.gem/credentials</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/917/1*numxEs9XIQQr51BKpOREtw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/694/1*S92zQdbr0yneNeqK8vcofA.png" /></figure><p>Thank you !</p><p>AshwinBorkar@</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=2c06333b7e6f" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Get association information between Models with ActiveRecord::Reflection.]]></title>
            <link>https://medium.com/@ashwinborkar1997/get-association-information-between-models-with-activerecord-reflection-0561f01d4325?source=rss-63a18ee16805------2</link>
            <guid isPermaLink="false">https://medium.com/p/0561f01d4325</guid>
            <dc:creator><![CDATA[Ashwin Borkar]]></dc:creator>
            <pubDate>Wed, 10 Apr 2024 10:37:44 GMT</pubDate>
            <atom:updated>2024-04-10T10:37:44.045Z</atom:updated>
            <content:encoded><![CDATA[<ul><li><a href="https://qiita.com/tags/ruby">Ruby</a></li><li><a href="https://qiita.com/tags/rails">Rails</a></li><li><a href="https://qiita.com/tags/activerecord">ActiveRecord</a></li></ul><h3>Introduction</h3><p>When handling information about the association between each Rails Model in the implementation, ActiveRecord provides methods to retrieve it and classes to manage that information.</p><p>This time, we will explain using the following Model as an example.</p><pre># Multiple books are linked to one Author, and multiple Pages are linked to one Book.<br># Author&#39;s primary key is code, Book&#39;s foreign key is author_code.<br>class Author &lt; ApplicationRecord<br>   self.primary_key = :code<br>   has_many :books, foreign_key: :author_code<br>end<br><br>class Book &lt; ApplicationRecord<br>   belongs_to :author, foreign_key: :author_code<br>   has_many :pages<br>end<br><br>class Page &lt; ApplicationRecord<br>   belongs_to :book<br>end</pre><h3>ActiveRecord::Reflection</h3><p>ActiveRecordA class that handles association information.</p><p>Expressing each relationship as an internal class AssociationReflection, it has subclasses such as HasManyReflection(has_many relationship) and (belongs_to relationship).BelongsToReflection</p><h3>reflect_on_association(association)</h3><p>associationObtain the association information for the argument model from the receiver&#39;s perspective .</p><pre>Book.reflect_on_association(:pages)<br># =&gt; (partially omitted)<br># #&lt;ActiveRecord::Reflection::HasManyReflection<br># @active_record=Book,<br># @name=:pages,<br># @options={}&gt;</pre><h3>reflect_on_all_associations</h3><p>Get all association information in an array.</p><h3>::reflections</h3><p>Get all association information by each association name keyand association information .valueHash</p><pre>Book.reflections<br>#=&gt; （一部省略）<br># {&quot;author&quot;=&gt;<br>#   #&lt;ActiveRecord::Reflection::BelongsToReflection<br>#    @active_record=Book,<br>#    @name=:author,<br>#    @options={:foreign_key=&gt;:author_code}&gt;,<br>#  &quot;pages&quot;=&gt;<br>#   #&lt;ActiveRecord::Reflection::HasManyReflection<br>#    @active_record=Book,<br>#    @name=:pages,<br>#    @options={}}</pre><h3>ActiveRecord::Reflection::AssociationReflection</h3><h3>foreign_key</h3><p>Get the foreign key of the related destination.</p><pre>reflection = Author.reflect_on_association(:books)<br>#=&gt; #&lt;ActiveRecord::Reflection::HasManyReflection&gt;<br>reflection.foreign_key<br>#=&gt; &quot;author_code&quot;</pre><h3>active_record_primary_key</h3><p>Get the primary key of the related source.</p><pre>reflection = Author.reflect_on_association(:books)<br>#=&gt; #&lt;ActiveRecord::Reflection::HasManyReflection&gt;<br>reflection.active_record_primary_key<br>#=&gt; &quot;code&quot;</pre><h3>association_primary_key</h3><p>Get the primary key of the related destination.</p><pre>reflection = Author.reflect_on_association(:books)<br>#=&gt; #&lt;ActiveRecord::Reflection::HasManyReflection&gt;<br>reflection.association_primary_key<br>#=&gt; &quot;id&quot;</pre><p>Thank you</p><p><a href="https://medium.com/u/63a18ee16805">Ashwin Borkar</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=0561f01d4325" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How to Configure Gmail SMTP To Send Emails From Your Applications in ruby on rails .]]></title>
            <link>https://medium.com/@ashwinborkar1997/how-to-configure-gmail-smtp-to-send-emails-from-your-applications-in-ruby-on-rails-0a512c766b4c?source=rss-63a18ee16805------2</link>
            <guid isPermaLink="false">https://medium.com/p/0a512c766b4c</guid>
            <dc:creator><![CDATA[Ashwin Borkar]]></dc:creator>
            <pubDate>Tue, 20 Feb 2024 12:56:48 GMT</pubDate>
            <atom:updated>2024-02-20T12:56:48.638Z</atom:updated>
            <content:encoded><![CDATA[<h3>How to Configure Gmail SMTP To Send Emails From Your Applications in ruby on rails .</h3><ul><li>ruby on rails version :- 7.1.0</li><li>ruby version :- 3.2.0</li></ul><p>In recent times, Gmail has removed the ability to enable <strong>Less App</strong> which is required to set up Gmail SMTP for sending emails in your applications if you are using the paid service.</p><p>In this article, we will find a workaround using the steps below:</p><ol><li><strong>First log in to your email account and navigate to the security section</strong></li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/700/0*0Y0__mm-QbvvuAZc.png" /></figure><p>2.<strong> Enable 2FA on your account</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/700/0*PSSD9mLbv-kBNCO3.png" /></figure><p>3. <strong>you need to create a new app password because your current Gmail password won’t work, in the security section, search for app password</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/700/0*PRgtJNsUzpxc-w9H.png" /></figure><p>This step will require you to log in again and then create an app-specific password, you can create a password for every application you need to configure SMTP for, enter the name of your application, click on create, and then complete the process.</p><p>You need to update the SMTP password in your application configuration, in my case, I am using .Ruby on rails, see the full code below:</p><p>4. go to the gemfile and add the content</p><pre>#for mail notification <br>gem &#39;exception_notification&#39;</pre><p>5. check the directory and add this content. <strong>/home/ashwin/project/hospital_mangment/config/environments/production.rb</strong></p><pre>Rails.application.configure do<br>  # Settings specified here will take precedence over those in config/application.rb.<br><br>  # Code is not reloaded between requests.<br>  config.cache_classes = true<br><br>  # Eager load code on boot. This eager loads most of Rails and<br>  # your application in memory, allowing both threaded web servers<br>  # and those relying on copy on write to perform better.<br>  # Rake tasks automatically ignore this option for performance.<br>  config.eager_load = true<br><br>  # Full error reports are disabled and caching is turned on.<br>  config.consider_all_requests_local       = false<br>  config.action_controller.perform_caching = true<br><br>  # Enable Rack::Cache to put a simple HTTP cache in front of your application<br>  # Add `rack-cache` to your Gemfile before enabling this.<br>  # For large-scale production use, consider using a caching reverse proxy like<br>  # NGINX, varnish or squid.<br>  # config.action_dispatch.rack_cache = true<br><br>  # Disable serving static files from the `/public` folder by default since<br>  # Apache or NGINX already handles this.<br>  config.serve_static_files = ENV[&#39;RAILS_SERVE_STATIC_FILES&#39;].present?<br><br>  # Compress JavaScripts and CSS.<br>  config.assets.js_compressor = :uglifier<br>  # config.assets.css_compressor = :sass<br><br>  # Do not fallback to assets pipeline if a precompiled asset is missed.<br>  config.assets.compile = true<br><br>  # Asset digests allow you to set far-future HTTP expiration dates on all assets,<br>  # yet still be able to expire them through the digest params.<br>  config.assets.digest = true<br><br>  # `config.assets.precompile` and `config.assets.version` have moved to config/initializers/assets.rb<br><br>  # Specifies the header that your server uses for sending files.<br>  # config.action_dispatch.x_sendfile_header = &#39;X-Sendfile&#39; # for Apache<br>  # config.action_dispatch.x_sendfile_header = &#39;X-Accel-Redirect&#39; # for NGINX<br><br>  # Force all access to the app over SSL, use Strict-Transport-Security, and use secure cookies.<br>  # config.force_ssl = true<br><br>  # Use the lowest log level to ensure availability of diagnostic information<br>  # when problems arise.<br>  config.log_level = :debug<br><br>  # Prepend all log lines with the following tags.<br>  # config.log_tags = [ :subdomain, :uuid ]<br><br>  # Use a different logger for distributed setups.<br>  # config.logger = ActiveSupport::TaggedLogging.new(SyslogLogger.new)<br><br>  # Use a different cache store in production.<br>  # config.cache_store = :mem_cache_store<br><br>  # Enable serving of images, stylesheets, and JavaScripts from an asset server.<br>  # config.action_controller.asset_host = &#39;http://assets.example.com&#39;<br><br>  # Ignore bad email addresses and do not raise email delivery errors.<br>  # Set this to true and configure the email server for immediate delivery to raise delivery errors.<br>  # config.action_mailer.raise_delivery_errors = false<br><br>  # Enable locale fallbacks for I18n (makes lookups for any locale fall back to<br>  # the I18n.default_locale when a translation cannot be found).<br>  config.i18n.fallbacks = true<br><br>  # Send deprecation notices to registered listeners.<br>  config.active_support.deprecation = :notify<br><br>  # Use default logging formatter so that PID and timestamp are not suppressed.<br>  config.log_formatter = ::Logger::Formatter.new<br><br>  # Do not dump schema after migrations.<br>  config.active_record.dump_schema_after_migration = false<br><br>  # mailers configurations<br>  config.action_mailer.raise_delivery_errors = true<br>  config.action_mailer.perform_deliveries = true<br>  config.action_mailer.default_url_options = { :host =&gt; &#39;xxx.yyy.zzz&#39; }<br>  config.action_mailer.delivery_method = :smtp<br>  config.action_mailer.smtp_settings = {<br>    :address =&gt; &quot;smtp.gmail.com&quot;,<br>    :port =&gt; &quot;587&quot;,<br>    :domain =&gt; &quot;google.com&quot;,<br>      :user_name =&gt; &quot;ashwinborkar1997@gmail.com&quot;,<br>      :password =&gt; &quot;ashwinborkar1997@1232&quot;,<br>      :authentication =&gt; &quot;plain&quot;,<br>      :enable_starttls_auto =&gt; true<br>    }<br><br>    # Exception Notification Configurations<br>    Rails.application.config.middleware.use ExceptionNotification::Rack,<br>    :email =&gt; {<br>      :email_prefix =&gt; &quot;[Hospital Mangment] &quot;,<br>      :sender_address =&gt; %{&quot;Production - Error on Production Server&quot; &lt;adminhospital@gmail.com&gt;},<br>      :exception_recipients =&gt; %w{ admin@gmail.com, ashwinborkar1997@gmail.com, superadmin@gmail.com}<br>    }<br>end</pre><p>now you can get the mail .</p><pre>A LoadError occurred in hospitals#create:<br><br>  cannot load such file -- uglifier<br><br><br>-------------------------------<br>Request:<br>-------------------------------<br><br>  * URL        : http://localhost:3001/hospitals/create<br>  * HTTP Method: GET<br>  * IP address : ::1<br>  * Parameters : {&quot;controller&quot;=&gt;&quot;tenpo_contract_details&quot;, &quot;action&quot;=&gt;&quot;create&quot;}<br>  * Timestamp  : 2024-02-20 12:36:13 UTC<br>  * Server : ashwin-borkar<br>    * Rails root : /home/ashwin/project/hospitals<br>  * Process: 84233<br><br>-------------------------------<br>Session:<br>-------------------------------<br><br>  * session id: &quot;8e6a686f09ecf55aeb08a5d115eac18e&quot;<br>  * data: {&quot;session_id&quot;=&gt;&quot;8e6a686f09ecf55aeb08a5d115eac18e&quot;,<br>   &quot;warden.user.user.key&quot;=&gt;[[1024], &quot;$2a$10$9gNaI2kZK/n2IsTWam/9g.&quot;],<br>   &quot;_csrf_token&quot;=&gt;&quot;3Q1FYipOghLwTwPbaXCSp_B6nH6pX5hNUawK9ueNzmY&quot;}<br><br>-------------------------------<br>Environment:<br>-------------------------------<br><br>  * GATEWAY_INTERFACE                                       : CGI/1.2<br>    * HTTP_ACCEPT                                             : text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.7<br>    * HTTP_ACCEPT_ENCODING                                    : gzip, deflate, br<br>    * HTTP_ACCEPT_LANGUAGE                                    : en-GB,en-US;q=0.9,en;q=0.8<br>    * HTTP_CONNECTION                                         : keep-alive<br>    * HTTP_COOKIE                                             : _session_id=d17562967e733743c2037cb7709b1efe; remember_user_token=eyJfcmFpbHMiOnsibWVzc2FnZSI6Ilcxc3hNREkwWFN3aUpESmhKREV3SkRsblRtRkpNbXRhU3k5dU1rbHpWRmRoYlM4NVp5NGlMQ0l4TnpBNE5ETXdOelEzTGpZek5USTRPRElpWFE9PSIsImV4cCI6IjIwMjQtMDMtMDVUMTI6MDU6NDcuNjM1WiIsInB1ciI6ImNvb2tpZS5yZW1lbWJlcl91c2VyX3Rva2VuIn19--881cc1c1fc4653498f1f6eeb91ded97b916790ad; _zdm_session=IddAtHgPAQvibigcigG6BoQ4LQc7cYcqH%2BHtW3STmWslGyY1XK89mpCmgHfgWyd6h959DDQfMW1k6TD7aMQuiX2p%2B0QCZ%2Bh3DQ3c7PSX2EYa2R7e2WlFrXAwcsNpYHZmvSa9Iox9YZ9vKfJWMkJ0UCJvVN%2FOfzl2SX5Dzxz8wezLrvk64v0g2o7nhhBVAItMqmO0VCewoY2Fq4YqVYwDpzlVkS18X4soeCu%2BlNCfZ5fPoz0aMpX0KFbMm0f31mC%2FmI6Tr2gfWrp6aux7VAzcXpn0gntjXJPoQWWEQ1wC1nJ9QBnB16IxiqRh34r8hkcRMQtQROAOOvLw4Myc85DVm8U%2FfkogdBr8bRxG0m%2BUs8l0xuBLzkfY8HWMvvftiECseXxSCP%2BXCm4%3D--m%2BK2DiRuDmmJVWHy--5wEcr2N82pvKk7EG3fYUeA%3D%3D<br>    * HTTP_HOST                                               : localhost:3001<br>    * HTTP_REFERER                                            : http://localhost:3001/hospitals/create<br>    * HTTP_SEC_CH_UA                                          : &quot;Not A(Brand&quot;;v=&quot;99&quot;, &quot;Google Chrome&quot;;v=&quot;121&quot;, &quot;Chromium&quot;;v=&quot;121&quot;<br>    * HTTP_SEC_CH_UA_MOBILE                                   : ?0<br>    * HTTP_SEC_CH_UA_PLATFORM                                 : &quot;Linux&quot;<br>    * HTTP_SEC_FETCH_DEST                                     : document<br>    * HTTP_SEC_FETCH_MODE                                     : navigate<br>    * HTTP_SEC_FETCH_SITE                                     : same-origin<br>    * HTTP_UPGRADE_INSECURE_REQUESTS                          : 1<br>    * HTTP_USER_AGENT                                         : Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/121.0.0.0 Safari/537.36<br>    * HTTP_VERSION                                            : HTTP/1.1<br>    * ORIGINAL_FULLPATH                                       : /hospitals/create<br>    * ORIGINAL_SCRIPT_NAME                                    :<br>    * PATH_INFO                                               : /hospitals/create<br>    * QUERY_STRING                                            :<br>    * REMOTE_ADDR                                             : ::1<br>    * REQUEST_METHOD                                          : GET<br>    * REQUEST_PATH                                            : /hospitals/create<br>    * REQUEST_URI                                             : /hospitals/create<br>    * ROUTES_17520_SCRIPT_NAME                                :<br>    * SCRIPT_NAME                                             :<br>    * SERVER_NAME                                             : localhost<br>    * SERVER_PORT                                             : 3001<br>    * SERVER_PROTOCOL                                         : HTTP/1.1<br>    * SERVER_SOFTWARE                                         : puma 5.6.5 Birdie&#39;s Version<br>    * action_controller.instance                              : #&lt;TenpoContractDetailsController:0x00007f833bdaac80&gt;<br>    * action_dispatch.authenticated_encrypted_cookie_salt     : [FILTERED]<br>    * action_dispatch.authorized_host                         : localhost<br>    * action_dispatch.backtrace_cleaner                       : #&lt;Rails::BacktraceCleaner:0x00007f8362999700&gt;<br>    * action_dispatch.content_security_policy                 :<br>    * action_dispatch.content_security_policy_nonce_directives:<br>    * action_dispatch.content_security_policy_nonce_generator :<br>    * action_dispatch.content_security_policy_report_only     : false<br>    * action_dispatch.cookies                                 : #&lt;ActionDispatch::Cookies::CookieJar:0x00007f833ba92368&gt;<br>    * action_dispatch.cookies_digest                          :<br>    * action_dispatch.cookies_rotations                       : #&lt;ActiveSupport::Messages::RotationConfiguration:0x00007f8369589028&gt;<br>    * action_dispatch.cookies_same_site_protection            : #&lt;Proc:0x00007f83628203b0 /home/ashwin/.rvm/gems/ruby-3.2.0/gems/railties-7.0.5/lib/rails/application.rb:609&gt;<br>    * action_dispatch.cookies_serializer                      : json<br>    * action_dispatch.encrypted_cookie_cipher                 : [FILTERED]<br>    * action_dispatch.encrypted_cookie_salt                   : [FILTERED]<br>    * action_dispatch.encrypted_signed_cookie_salt            : [FILTERED]<br>    * action_dispatch.http_auth_salt                          : [FILTERED]<br>    * action_dispatch.key_generator                           : #&lt;ActiveSupport::CachingKeyGenerator:0x00007f8361caab20&gt;<br>    * action_dispatch.log_rescued_responses                   : true<br>    * action_dispatch.logger                                  : #&lt;ActiveSupport::Logger:0x00007f83633f4f10&gt;<br>    * action_dispatch.parameter_filter                        : [:passw, :secret, :token, :_key, :crypt, :salt, :certificate, :otp, :ssn, &quot;encrypted_rich_text.body&quot;]<br>    * action_dispatch.permissions_policy                      :<br>    * action_dispatch.redirect_filter                         : []<br>    * action_dispatch.remote_ip                               : ::1<br>    * action_dispatch.request.content_type                    :<br>    * action_dispatch.request.formats                         : [#&lt;Mime::Type:0x00007f8363d46050 @synonyms=[&quot;application/xhtml+xml&quot;], @symbol=:html, @string=&quot;text/html&quot;, @hash=4371820914552910327&gt;]<br>    * action_dispatch.request.parameters                      : {&quot;controller&quot;=&gt;&quot;hostpitals&quot;, &quot;action&quot;=&gt;&quot;create&quot;}<br>    * action_dispatch.request.path_parameters                 : {:controller=&gt;&quot;hostpitals&quot;, :action=&gt;&quot;create&quot;}<br>    * action_dispatch.request.query_parameters                : {}<br>    * action_dispatch.request.request_parameters              : {}<br>    * action_dispatch.request.unsigned_session_cookie         : {&quot;session_id&quot;=&gt;&quot;8e6a686f09ecf55aeb08a5d115eac18e&quot;, &quot;warden.user.user.key&quot;=&gt;[[1024], &quot;$2a$10$9gNaI2kZK/n2IsTWam/9g.&quot;], &quot;_csrf_token&quot;=&gt;&quot;[FILTERED]&quot;}<br>    * action_dispatch.request_id                              : 850c76ed-9ba4-4616-a3aa-208a207f72e2<br>    * action_dispatch.routes                                  : #&lt;ActionDispatch::Routing::RouteSet:0x00007f8363393ad0&gt;<br>    * action_dispatch.secret_key_base                         : [FILTERED]<br>    * action_dispatch.show_detailed_exceptions                : false<br>    * action_dispatch.show_exceptions                         : true<br>    * action_dispatch.signed_cookie_digest                    :<br>    * action_dispatch.signed_cookie_salt                      : [FILTERED]<br>    * action_dispatch.use_authenticated_cookie_encryption     : [FILTERED]<br>    * action_dispatch.use_cookies_with_metadata               : true<br>    * puma.config                                             : #&lt;Puma::Configuration:0x00007f8361e19290&gt;<br>    * puma.request_body_wait                                  : 0<br>    * puma.socket                                             : #&lt;TCPSocket:0x00007f8361d76270&gt;<br>    * rack.after_reply                                        : []<br>    * rack.errors                                             : #&lt;IO:0x00007f8369548f28&gt;<br>    * rack.hijack                                             : #&lt;Puma::Client:0x00007f8365026198&gt;<br>    * rack.hijack?                                            : true<br>    * rack.input                                              : #&lt;Puma::NullIO:0x00007f8363d71570&gt;<br>    * rack.multiprocess                                       : false<br>    * rack.multithread                                        : true<br>    * rack.request.cookie_hash                                : {&quot;_session_id&quot;=&gt;&quot;d17562967e733743c2037cb7709b1efe&quot;, &quot;remember_user_token&quot;=&gt;&quot;[FILTERED]&quot;, &quot;_zdm_session&quot;=&gt;&quot;IddAtHgPAQvibigcigG6BoQ4LQc7cYcqH+HtW3STmWslGyY1XK89mpCmgHfgWyd6h959DDQfMW1k6TD7aMQuiX2p+0QCZ+h3DQ3c7PSX2EYa2R7e2WlFrXAwcsNpYHZmvSa9Iox9YZ9vKfJWMkJ0UCJvVN/Ofzl2SX5Dzxz8wezLrvk64v0g2o7nhhBVAItMqm...<br>    * rack.request.cookie_string                              : _session_id=d17562967e733743c2037cb7709b1efe; remember_user_token=eyJfcmFpbHMiOnsibWVzc2FnZSI6Ilcxc3hNREkwWFN3aUpESmhKREV3SkRsblRtRkpNbXRhU3k5dU1rbHpWRmRoYlM4NVp5NGlMQ0l4TnpBNE5ETXdOelEzTGpZek5USTRPRElpWFE9PSIsImV4cCI6IjIwMjQtMDMtMDVUMTI6MDU6NDcuNjM1WiIsInB1ciI6ImNvb2tpZS5yZW1lbWJlcl91c2VyX3Rva2VuIn19--881cc1c1fc4653498f1f6eeb91ded97b916790ad; _zdm_session=IddAtHgPAQvibigcigG6BoQ4LQc7cYcqH%2BHtW3STmWslGyY1XK89mpCmgHfgWyd6h959DDQfMW1k6TD7aMQuiX2p%2B0QCZ%2Bh3DQ3c7PSX2EYa2R7e2WlFrXAwcsNpYHZmvSa9Iox9YZ9vKfJWMkJ0UCJvVN%2FOfzl2SX5Dzxz8wezLrvk64v0g2o7nhhBVAItMqmO0VCewoY2Fq4YqVYwDpzlVkS18X4soeCu%2BlNCfZ5fPoz0aMpX0KFbMm0f31mC%2FmI6Tr2gfWrp6aux7VAzcXpn0gntjXJPoQWWEQ1wC1nJ9QBnB16IxiqRh34r8hkcRMQtQROAOOvLw4Myc85DVm8U%2FfkogdBr8bRxG0m%2BUs8l0xuBLzkfY8HWMvvftiECseXxSCP%2BXCm4%3D--m%2BK2DiRuDmmJVWHy--5wEcr2N82pvKk7EG3fYUeA%3D%3D<br>    * rack.request.query_hash                                 : {}<br>    * rack.request.query_string                               :<br>    * rack.run_once                                           : false<br>    * rack.session                                            : #&lt;ActionDispatch::Request::Session:0x00007f833ba93268&gt;<br>    * rack.session.options                                    : #&lt;ActionDispatch::Request::Session::Options:0x00007f833ba66f88&gt;<br>    * rack.tempfiles                                          : []<br>    * rack.url_scheme                                         : http<br>    * rack.version                                            : [1, 6]<br>    * warden                                                  : Warden::Proxy:36100 @config={:default_scope=&gt;:user, :scope_defaults=&gt;{}, :default_strategies=&gt;{:user=&gt;[:rememberable, :database_authenticatable]}, :intercept_401=&gt;false, :failure_app=&gt;#&lt;Devise::Delegator:0x00007f8361f2da28&gt;}</pre><p>Thank you !</p><p><strong>Ashwin Borkar</strong></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=0a512c766b4c" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Ruby On rails Using phlex gem]]></title>
            <link>https://medium.com/@ashwinborkar1997/ruby-on-rails-using-phlex-gem-5603ab87a4bf?source=rss-63a18ee16805------2</link>
            <guid isPermaLink="false">https://medium.com/p/5603ab87a4bf</guid>
            <dc:creator><![CDATA[Ashwin Borkar]]></dc:creator>
            <pubDate>Mon, 12 Feb 2024 13:23:13 GMT</pubDate>
            <atom:updated>2024-02-12T13:23:13.930Z</atom:updated>
            <content:encoded><![CDATA[<h3>Phlex 💪</h3><p>Phlex is a <a href="https://rubygems.org/gems/phlex">Ruby gem</a> for building fast object-oriented HTML and SVG components. Views are described using Ruby constructs: <em>methods</em>, <em>keyword arguments</em> and <em>blocks</em>, which directly correspond to the output. For example, this is how you might describe an HTML &lt;nav&gt; with a list of links:</p><pre>class Nav &lt; Phlex::HTML<br>  def template<br>    nav(class: &quot;main-nav&quot;) {<br>    ul {<br>    li { a(href: &quot;/&quot;) { &quot;Home&quot; } }<br>    li { a(href: &quot;/about&quot;) { &quot;About&quot; } }<br>    li { a(href: &quot;/contact&quot;) { &quot;Contact&quot; } }<br>   }<br>  }<br>  end<br>end</pre><pre>&lt;nav class=&quot;main-nav&quot;&gt;<br>  &lt;ul&gt;<br>    &lt;li&gt;&lt;a href=&quot;/&quot;&gt;Home&lt;/a&gt;&lt;/li&gt;<br>    &lt;li&gt;&lt;a href=&quot;/about&quot;&gt;About&lt;/a&gt;&lt;/li&gt;<br>    &lt;li&gt;&lt;a href=&quot;/contact&quot;&gt;Contact&lt;/a&gt;&lt;/li&gt;<br>  &lt;/ul&gt;<br>&lt;/nav&gt;</pre><h3>Why render HTML in Ruby?</h3><p>Building components in Ruby makes it possible to build powerful abstractions. The Nav menu above could be refactored into a Ruby class to allow developers to add items to the menu without needing to understand the underlying HTML.</p><pre>class Nav &lt; Phlex::HTML<br>  def template(&amp;content)<br>   nav(class: &quot;main-nav&quot;) {<br>   ul(&amp;content)<br>   }<br>  end<br><br>  def item(url, &amp;content)<br>   li { a(href: url, &amp;content) }<br>  end<br>end</pre><pre>&lt;nav class=&quot;main-nav&quot;&gt;<br>  &lt;ul&gt;<br>    &lt;li&gt;&lt;a href=&quot;/&quot;&gt;Home&lt;/a&gt;&lt;/li&gt;<br>    &lt;li&gt;&lt;a href=&quot;/about&quot;&gt;About&lt;/a&gt;&lt;/li&gt;<br>    &lt;li&gt;&lt;a href=&quot;/contact&quot;&gt;Contact&lt;/a&gt;&lt;/li&gt;<br>  &lt;/ul&gt;<br>&lt;/nav&gt;</pre><p>The component can be called from Ruby or Erb without a bunch of &lt;% %&gt; tags.</p><pre>render Nav.new do |nav|<br> nav.item(&quot;/&quot;) { &quot;Home&quot; }<br> nav.item(&quot;/about&quot;) { &quot;About&quot; }<br> nav.item(&quot;/contact&quot;) { &quot;Contact&quot; }<br>end</pre><p>Since the component is just a Ruby class, it can be extended with inheritence and modules. Let’s create a subclass that works with Tailwind CSS.</p><pre>class TailwindNav &lt; Nav<br> def template(&amp;content) = nav(class: &quot;flex flex-row gap-4&quot;, &amp;content)<br><br> def item(url, &amp;content)<br>   a(href: url, class: &quot;text-underline&quot;, &amp;content)<br> end<br>end</pre><pre>&lt;nav class=&quot;flex flex-row gap-4&quot;&gt;&lt;a href=&quot;/&quot; class=&quot;text-underline&quot;&gt;Home&lt;/a&gt;&lt;a href=&quot;/about&quot; class=&quot;text-underline&quot;&gt;About&lt;/a&gt;&lt;a href=&quot;/contact&quot; class=&quot;text-underline&quot;&gt;Contact&lt;/a&gt;&lt;/nav&gt;</pre><p>Your view data, code, and markup live together in the same place making it easier to reason through an application’s UI. Since views are just Ruby, you get more flexibility than templating languages like Erb, Slim, Haml, and Liquid.</p><h3>Getting Started</h3><h3>Installation</h3><p>Install Phlex to your project by running:</p><pre>bundle add phlex</pre><pre>gem &quot;phlex&quot;</pre><p>and automatically run bundle install</p><h3>What’s a view?</h3><p>Views are Ruby objects that represent a piece of output from your app. We plan to support various different types of output — such as JSON, XML and SVG — but for now, we’re focusing on HTML.</p><p>Views can have an initialize method that dictates which arguments the view accepts and is responsible for setting everything up — usually assigning instance variables for use in the template.</p><p>The template is a special method that’s called when rendering a view. The template method determines the output of the view by calling methods that append to the output.</p><p>Instance methods perform important calculations or encapsulate a small part of the template. Public instance methods can expose an interface that’s yielded to the parent when rendering.</p><h3>HTML</h3><h3>HTML Views</h3><p>You can create an HTML view by subclassing Phlex::HTML and defining a template instance method.</p><pre>class Hello &lt; Phlex::HTML<br>	def template<br>		h1 { &quot;👋 Hello World!&quot; }<br>	end<br>end</pre><pre>&lt;h1&gt;👋 Hello World!&lt;/h1&gt;</pre><p>The template method determines what your view will output when its rendered. The above example calls the h1 method which outputs an &lt;h1&gt; tag.</p><h3>Accepting arguments</h3><p>You can define an <em>initializer</em> for your views just like any other Ruby class. Let’s make our Hello view take a name as a keyword argument, save it in an instance variable and render that variable in the template.</p><p>We’ll render this view with the arguments name: &quot;Joel&quot; and see what it produces.</p><pre>Class Hello &lt; Phlex::HTML<br> def initialize(name:)<br>  @name = name<br> end<br> def template<br>  h1 { &quot;👋 Hello #{@name}!&quot; }<br> end<br>end<br>&lt;h1&gt;👋 Hello Joel!&lt;/h1&gt;</pre><h3>Rendering views</h3><p>Views can render other views in their templates using the render method. Let&#39;s try rendering a couple of instances of this Hello view from a new Example view and look at the output of the Example view.</p><pre>class Example &lt; Phlex::HTML<br>	def template<br>	  render Hello.new(name: &quot;Joel&quot;)<br>	  render Hello.new(name: &quot;Alexandre&quot;)<br>	end<br>end</pre><pre>&lt;h1&gt;👋 Hello Joel!&lt;/h1&gt;<br>&lt;h1&gt;👋 Hello Alexandre!&lt;/h1&gt;</pre><h3>Content</h3><p>Views can also yield content blocks, which can be passed in when rendering. Let’s make a Card component that yields content in an &lt;article&gt; element with a drop-shadow class on it.</p><pre>class Card &lt; Phlex::HTML<br> def template<br>  article(class: &quot;drop-shadow&quot;) {<br>   yield<br>  }<br> end<br>end<br>class Example &lt; Phlex::HTML<br> def template<br>  render(Card.new) {<br>   h1 { &quot;👋 Hello!&quot; }<br>  }<br> end<br>end<br>&lt;article class=&quot;drop-shadow&quot;&gt;<br>  &lt;h1&gt;👋 Hello!&lt;/h1&gt;<br>&lt;/article&gt;</pre><p>The Example view renders a Card and passes it a block with an &lt;h1&gt; tag.</p><p>Looking at the output of the Example view, we can see the &lt;h1&gt; element was rendered inside the &lt;article&gt; element from the Card view.</p><h3>Delegating content</h3><p>Since the block of content was the only thing we need in the &lt;article&gt; element, we could have just passed the content block directly to the element instead.</p><pre>class Card &lt; Phlex::HTML<br>	def template(&amp;)<br>		article(class: &quot;drop-shadow&quot;, &amp;)<br>	end<br>end</pre><h3>Hooks</h3><p>You can hook into the rendering process by overriding before_template and after_template which are called immediately before and after the template is rendered.</p><p>You should always call super from these methods to allow for inherited callbacks.</p><pre>class Example &lt; Phlex::HTML<br> def before_template<br>  h1 { &quot;Before&quot; }<br>  super<br> end<br> def template<br>  h2 { &quot;Hello World!&quot; }<br> end<br> def after_template<br>  super<br>  h3 { &quot;After&quot; }<br> end<br>end<br>&lt;h1&gt;Before&lt;/h1&gt;<br>&lt;h2&gt;Hello World!&lt;/h2&gt;<br>&lt;h3&gt;After&lt;/h3&gt;</pre><h3>Tags</h3><h3>HTML Tags</h3><p>Phlex::HTML comes with methods that correspond to the most common HTML tags. You’ve seen the h1 tag in the previous section.</p><h3>Content</h3><p>You pass content as a block to a tag method. If the return value of the block is a String, Symbol, Integer or Float and no output methods were used, the return value will be output as <em>text</em>.</p><pre><br>class Greeting &lt; Phlex::HTML<br> def template<br>  h1 { &quot;👋 Hello World!&quot; }<br> end<br>end<br>&lt;h1&gt;👋 Hello World!&lt;/h1&gt;</pre><h3>Attributes</h3><p>You can add attributes to HTML elements by passing keyword arguments to the methods.</p><pre>class Greeting &lt; Phlex::HTML<br> def template<br>  h1(class: &quot;text-xl font-bold&quot;) { &quot;👋 Hello World!&quot; }<br> end<br>end<br>&lt;h1 class=&quot;text-xl font-bold&quot;&gt;👋 Hello World!&lt;/h1&gt;</pre><p>Underscores _ are automatically converted to dashes - for Symbol keys. If you need to use an underscore in an attribute name, you can use a String key instead.</p><pre>class Greeting &lt; Phlex::HTML<br> def template<br>  h1(foo_bar: &quot;hello&quot;) { &quot;👋 Hello World!&quot; }<br>  h1(&quot;foo_bar&quot; =&gt; &quot;hello&quot;) { &quot;👋 Hello World!&quot; }<br> end<br>end<br>&lt;h1 foo-bar=&quot;hello&quot;&gt;👋 Hello World!&lt;/h1&gt;<br>&lt;h1 foo_bar=&quot;hello&quot;&gt;👋 Hello World!&lt;/h1&gt;</pre><h3>Hash attributes</h3><p>You can pass a Hash as an attribute value and it will be flattened with a dash - between each level.</p><pre>class Greeting &lt; Phlex::HTML<br> def template<br>  div(data: { controller: &quot;hello&quot; }) {<br>   # ...<br>  }<br> end<br>end<br>&lt;div data-controller=&quot;hello&quot;&gt;&lt;/div&gt;</pre><h3>Boolean attributes</h3><p>When an attribute value is true, the attribute name will be output without a value; when <em>falsy</em>, the attribute isn’t output at all. You can use the strings &quot;true&quot; and &quot;false&quot; as values for non-boolean attributes.</p><pre>class ChannelControls &lt; Phlex::HTML<br> def template<br>  input(<br>   value: &quot;1&quot;,<br>   name: &quot;channel&quot;,<br>   type: &quot;radio&quot;,<br>   checked: true<br>  )<br>  input(<br>   value: &quot;2&quot;,<br>   name: &quot;channel&quot;,<br>   type: &quot;radio&quot;,<br>   checked: false<br>  )<br> end<br>end</pre><pre>&lt;input value=&quot;1&quot; name=&quot;channel&quot; type=&quot;radio&quot; checked&gt;&lt;input value=&quot;2&quot; name=&quot;channel&quot; type=&quot;radio&quot;&gt;</pre><h3>The template tag</h3><p>Because the template method is used to define the view template itself, you&#39;ll need to use the method template_tag if you want to to render an HTML &lt;template&gt; tag.</p><pre>class TemplateExample &lt; Phlex::HTML<br> def template<br>  template_tag {<br>   img src: &quot;hidden.jpg&quot;, alt: &quot;A hidden image.&quot;<br>  }<br> end<br>end<br>&lt;template&gt;&lt;img src=&quot;hidden.jpg&quot; alt=&quot;A hidden image.&quot;&gt;&lt;/template&gt;</pre><h3>Registering custom tags</h3><p>You can register custom elements with the register_element macro. The custom element will only be available in the view where it is registered and subclasses of that view.</p><pre>class CustomTagExample &lt; Phlex::HTML<br> register_element :trix_editor<br> def template<br>  trix_editor input: &quot;content&quot;, autofocus: true<br> end<br>end<br>&lt;trix-editor input=&quot;content&quot; autofocus&gt;&lt;/trix-editor&gt;</pre><h3>Helpers</h3><h3>HTML Helpers</h3><h3>Stand-alone text</h3><p>You can output text content without wrapping it in an element by using the plain method. It accepts a single argument which can be a String, Symbol, Integer or Float.</p><pre>class Heading &lt; Phlex::HTML<br> def template<br>  h1 do<br>   strong { &quot;Hello &quot; }<br>   plain &quot;World!&quot;<br>  end<br> end<br>end<br>&lt;h1&gt;&lt;strong&gt;Hello &lt;/strong&gt;World!&lt;/h1&gt;</pre><h3>Whitespace</h3><p>If you need to add whitespace, you can use the whitespace method. This is useful for adding space between <em>inline</em> elements to allow them to wrap.</p><pre>class Links &lt; Phlex::HTML<br>	def template<br>		a(href: &quot;/&quot;) { &quot;Home&quot; }<br>		whitespace<br>		a(href: &quot;/about&quot;) { &quot;About&quot; }<br>		whitespace<br>		a(href: &quot;/contact&quot;) { &quot;Contact&quot; }<br>	end<br>end</pre><pre>&lt;a href=&quot;/&quot;&gt;Home&lt;/a&gt; &lt;a href=&quot;/about&quot;&gt;About&lt;/a&gt; &lt;a href=&quot;/contact&quot;&gt;Contact&lt;/a&gt;</pre><p>If you pass a block to whitespace, the content is wrapped in whitespace on either side.</p><pre>whitespace { a(href: &quot;/&quot;) { &quot;Home&quot; } }</pre><h3>Comments</h3><p>The comment method takes a block and wraps the content in an HTML comment.</p><pre>comment { &quot;Hello&quot; }</pre><h3>Conditional tokens</h3><p>The tokens method helps you define conditional HTML attribute tokens such as CSS classes. You can use it to combine multiple tokens together.</p><pre>tokens(&quot;a&quot;, &quot;b&quot;, &quot;c&quot;) # → &quot;a b c&quot;</pre><p>You can use keyword arguments to specify the conditions for specific tokens. A condition can be a Proc or Symbol that maps to an instance method. The :active? Symbol for example maps to the active? instance method.</p><pre>tokens(<br>	-&gt; { true } =&gt; &quot;foo&quot;,<br>	-&gt; { false } =&gt; &quot;bar&quot;<br>) # → &quot;foo&quot;</pre><p>Here we have a Link view that produces an &lt;a&gt; tag with the CSS class nav-item. If the link is <em>active</em>, we also apply the CSS class active.</p><pre>class Link &lt; Phlex::HTML<br> def initialize(text, to:, active:)<br>  @text = text<br>  @to = to<br>  @active = active<br> end<br> def template<br>  a(href: @to, class: tokens(&quot;nav-item&quot;,<br>    active?: &quot;active&quot;)) { @text }<br> end<br> private<br> def active? = @active<br>end<br>class TokensExample &lt; Phlex::HTML<br> def template<br>  nav {<br>   ul {<br>    li { render Link.new(&quot;Home&quot;, to: &quot;/&quot;, active: true) }<br>    li { render Link.new(&quot;About&quot;, to: &quot;/about&quot;, active: false) }<br>   }<br>  }<br> end<br>end<br>&lt;nav&gt;<br>  &lt;ul&gt;<br>    &lt;li&gt;&lt;a href=&quot;/&quot; class=&quot;nav-item active&quot;&gt;Home&lt;/a&gt;&lt;/li&gt;<br>    &lt;li&gt;&lt;a href=&quot;/about&quot; class=&quot;nav-item&quot;&gt;About&lt;/a&gt;&lt;/li&gt;<br>  &lt;/ul&gt;<br>&lt;/nav&gt;</pre><h3>Conditional classes</h3><p>The classes method helps to create a token list of CSS classes. This method returns a Hash with the key :class and the value as the result of tokens, allowing you to destructure it into a keyword argument using the ** prefix operator.</p><pre>class Link &lt; Phlex::HTML<br> def initialize(text, to:, active:)<br>  @text = text<br>  @to = to<br>  @active = active<br> end<br> def template<br>  a(href: @to, **classes(&quot;nav-item&quot;,<br>   active?: &quot;active&quot;)) { @text }<br> end<br> private<br> def active? = @active<br>end<br>class ClassesExample &lt; Phlex::HTML<br> def template<br>  nav {<br>   ul {<br>    li { render Link.new(&quot;Home&quot;, to: &quot;/&quot;, active: true) }<br>    li { render Link.new(&quot;About&quot;, to: &quot;/about&quot;, active: false) }<br>   }<br>  }<br> end<br>end<br>&lt;nav&gt;<br>  &lt;ul&gt;<br>    &lt;li&gt;&lt;a href=&quot;/&quot; class=&quot;nav-item active&quot;&gt;Home&lt;/a&gt;&lt;/li&gt;<br>    &lt;li&gt;&lt;a href=&quot;/about&quot; class=&quot;nav-item&quot;&gt;About&lt;/a&gt;&lt;/li&gt;<br>  &lt;/ul&gt;<br>&lt;/nav&gt;</pre><h3>Unsafe output</h3><p>unsafe_raw takes a String and outputs it without any safety or HTML escaping. You should <em>never</em> use this method with any string that could come from an untrusted person. In fact, you should pretty much never use this method. If you do, don’t come crying when someone hacks your website.</p><p>If you think you need to use unsafe_raw, maybe <a href="https://github.com/phlex-ruby/phlex/discussions/new">open a discussion thread</a> for other ideas.</p><h3>Slots</h3><p>You can build reusable &amp; composable Phlex views.</p><p>For example, you may need to define multiple sections (slots) in a view. This can be accomplished by defining public instance methods on the view that accept blocks:</p><pre>class Card &lt; Phlex::HTML<br> def template(&amp;)<br>  article(class: &quot;card&quot;, &amp;)<br> end<br> def title(&amp;)<br>  div(class: &quot;title&quot;, &amp;)<br> end<br> def body(&amp;)<br>  div(class: &quot;body&quot;, &amp;)<br> end<br>end<br>class CardExample &lt; Phlex::HTML<br> def template<br>  render Card.new do |card|<br>   card.title do<br>    h1 { &quot;Title&quot; }<br>   end<br>   card.body do<br>    p { &quot;Body&quot; }<br>   end<br>  end<br> end<br>end<br>&lt;article class=&quot;card&quot;&gt;<br>  &lt;div class=&quot;title&quot;&gt;<br>    &lt;h1&gt;Title&lt;/h1&gt;<br>  &lt;/div&gt;<br>  &lt;div class=&quot;body&quot;&gt;<br>    &lt;p&gt;Body&lt;/p&gt;<br>  &lt;/div&gt;<br>&lt;/article&gt;</pre><p>One caveat of defining the view this way is title and body could be called in any order. This offers flexibility, but what if you need to make sure your markup is output in a consistent order?</p><p>First, include Phlex::DeferredRender in your view. This changes the behavior of template so it does not receive a block and is yielded early. Then use public methods to save blocks, passing them to back to the template at render time.</p><pre>class List &lt; Phlex::HTML<br> include Phlex::DeferredRender<br> def initialize<br>  @items = []<br> end<br> def template<br>  if @header<br>   h1(class: &quot;header&quot;, &amp;@header)<br>  end<br>  ul do<br>   @items.each do |item|<br>    li { render(item) }<br>   end<br>  end<br> end<br> def header(&amp;block)<br>  @header = block<br> end<br> def with_item(&amp;content)<br>  @items &lt;&lt; content<br> end<br>end<br>class ListExample &lt; Phlex::HTML<br> def template<br>  render List.new do |list|<br>   list.header do<br>    &quot;Header&quot;<br>   end<br>   list.with_item do<br>    &quot;One&quot;<br>   end<br>   list.with_item do<br>    &quot;two&quot;<br>   end<br>  end<br> end<br>end<br>&lt;h1 class=&quot;header&quot;&gt;Header&lt;/h1&gt;<br>&lt;ul&gt;<br>  &lt;li&gt;One&lt;/li&gt;<br>  &lt;li&gt;two&lt;/li&gt;<br>&lt;/ul&gt;</pre><h3>Testing Introduction</h3><h3>Testing Phlex Views</h3><p>The Phlex::Testing::ViewHelper module defines render allowing you to render Phlex views directly in your tests and make assertions against the output.</p><p>You’ll need to require phlex/testing/view_helper and include Phlex::Testing::ViewHelper your test.</p><pre>require &quot;phlex/testing/view_helper&quot;<br>class TestHello &lt; Minitest::Test<br> include Phlex::Testing::ViewHelper<br> def test_hello_output_includes_name<br>  output = render Hello.new(&quot;Joel&quot;)<br>  assert_equal &quot;&lt;h1&gt;Hello Joel&lt;/h1&gt;&quot;, output<br> end<br>end<br>class Hello &lt; Phlex::HTML<br> def initialize(name)<br>  @name = name<br> end<br> def template<br>  h1 { &quot;Hello #{@name}&quot; }<br> end<br>end</pre><h3>Nokogiri</h3><h3>Testing HTML Views with Nokogiri [beta]</h3><p>The <a href="https://rubygems.org/gems/phlex-testing-nokogiri">phlex-testing-nokogiri</a> gem provides helpers for working with rendered views as <a href="https://nokogiri.org/">Nokogiri</a> documents and fragments.</p><h3>Installation</h3><p>Add the following to the test group in your Gemfile and run bundle install.</p><pre>gem &quot;phlex-testing-nokogiri&quot;</pre><h3>Testing Documents</h3><p>If your view represents a whole HTML document, you can require phlex/testing/nokogiri and include the Phlex::Testing::Nokogiri::DocumentHelper module to render your view as Nokogiri::Document using the render method.</p><pre>require &quot;phlex/testing/nokogiri&quot;<br>class TestExample &lt; Minitest::Test<br> include Phlex::Testing::Nokogiri::DocumentHelper<br> def test_example<br>  output = render Example.new<br>  assert_equal &quot;Hello Joel&quot;, output.css(&quot;h1&quot;).text<br> end<br>end<br>class Hello &lt; Phlex::HTML<br> def initialize(name)<br>  @name = name<br> end<br> def template<br>  h1 { &quot;Hello #{@name}&quot; }<br> end<br>end</pre><p>If your view represents a fragment (partial), you can require phlex/testing/nokogiri and include the Phlex::Testing::Nokogiri::FragmentHelper module to render your view as Nokogiri::Fragment with the render method.</p><pre>require &quot;phlex/testing/nokogiri&quot;<br>class TestExample &lt; Minitest::Test<br> include Phlex::Testing::Nokogiri::FragmentHelper<br> def test_example<br>  output = render Example.new(&quot;Joel&quot;)<br>  assert_equal &quot;Hello Joel&quot;, output.css(&quot;h1&quot;).text<br> end<br>end</pre><pre>class Hello &lt; Phlex::HTML<br> def initialize(name)<br>  @name = name<br> end<br> def template<br>  h1 { &quot;Hello #{@name}&quot; }<br> end<br>end</pre><h3>Capybara</h3><h3>Testing with Capybara [beta]</h3><p>The <a href="https://rubygems.org/gems/phlex-testing-capybara">phlex-testing-capybara</a> gem provides a test helper that lets you use <a href="http://teamcapybara.github.io/capybara/">Capybara</a> matchers.</p><h3>Installation</h3><p>Add the following to the test group in your Gemfile and run bundle install.</p><pre>gem &quot;phlex-testing-capybara&quot;</pre><h3>Usage</h3><p>You’ll need to require phlex/testing/capybara and include Phlex::Testing::Capybara::ViewHelper.</p><p>The render method will return a Capybara::Node::Simple and set the page attribute to the result.</p><pre>require &quot;phlex/testing/capybara&quot;</pre><pre>class TestExample &lt; Minitest::Test<br>	include Phlex::Testing::Capybara::ViewHelper</pre><pre>	def test_example<br>		render Example.new(&quot;Joel&quot;)<br>		assert_selector &quot;h1&quot;, text: &quot;Hello Joel&quot;<br>	end<br>end</pre><pre>class Hello &lt; Phlex::HTML<br> def initialize(name)<br>  @name = name<br> end<br> def template<br>  h1 { &quot;Hello #{@name}&quot; }<br> end<br>end</pre><h3>Testing Rails</h3><h3>Testing Phlex views in Rails</h3><p>When you include Phlex::Testing::Rails::ViewHelper, views rendered in the test will have a view context, so they can use Rails helpers.</p><h3>Rails Introduction</h3><h3>Getting started with Phlex on Rails</h3><p>While Phlex can be used in any Ruby project, it’s especially great with <a href="https://rubyonrails.org/">Rails</a>. But before we get into the details, it’s important to understand that Phlex is very different from <a href="https://guides.rubyonrails.org/action_view_overview.html">ActionView</a> and <a href="https://viewcomponent.org/">ViewComponent</a>.</p><h3>Setup</h3><p>To use Phlex with Rails, you’ll need to install the <a href="https://rubygems.org/gems/phlex-rails">phlex-rails</a> gem. Add the following to your Gemfile and run bundle install.</p><pre>gem &quot;phlex-rails&quot;</pre><p>Note, you do not need to install phlex separately because phlex is a dependency of phlex-rails.</p><p>Once the gem is installed, run the install generator.</p><pre>bin/rails generate phlex:install</pre><p>This script will:</p><ol><li>update config/application.rb to include app/views, app/views/components, and app/views/layouts in your auto-load paths;</li><li>generate views/application_view.rb</li><li>generate views/layouts/application_layout.rb</li><li>generate views/components/application_component.rb</li></ol><p>ApplicationComponent is your base component which all your other components inherit from. By default, ApplicationView inherits from ApplicationComponent.</p><h3>Generators</h3><h3>Rails Generators</h3><h3>Component</h3><pre>bin/rails g phlex:component Card</pre><p>This will generate a CardComponent in card_component.rb under app/views/components.</p><h3>View</h3><pre>bin/rails g phlex:view Articles::Index</pre><p>This will generate an Articles::IndexView in index_view.rb under app/views/articles.</p><h3>Controller</h3><pre>bin/rails g phlex:controller Articles index show</pre><p>This will generate an ArticlesController in app/controllers. It will have the actions index and show, which will render the views Articles::IndexView and Articles::ShowView generated in index_view.rb and show_view.rb under app/views/articles.</p><h3>Rendering Views</h3><h3>Render Phlex views in Rails</h3><p>You can render a Phlex view from your Rails controller actions or other views — Phlex, ActionView or ViewComponent.</p><p>Instead of implicitly rendering an ERB template with automatic access to all your controller instance variables, you’ll need to explicitly render Phlex views from your controller action methods.</p><pre>class ArticlesController &lt; ApplicationController<br>	layout -&gt; { ApplicationLayout }<br> def index<br>  render Articles::IndexView.new(<br>   articles: Article.all.load_async<br>  )<br> end<br> def show<br>  render Articles::ShowView.new(<br>   article: Article.find(params[:id])<br>  )<br> end<br>end</pre><h3>Layouts</h3><h3>Layouts in Rails</h3><p>If you ran the install generator, you should have an ApplicationLayout file under app/views/layouts/application_layout.rb.</p><p>You can configure a controller to use this layout with the layout method. Phlex layouts are even compatible with non-Phlex views.</p><pre>class FooController &lt; ApplicationController<br>	layout -&gt; { ApplicationLayout }<br> def index<br>   render Foo::IndexView<br> end<br>end</pre><h3>Yielding content</h3><p>Rails doesn’t provide a mechanism for passing arguments to a layout component, but your layout can yield content provided by content_for.</p><pre>class ApplicationLayout &lt; Phlex::HTML<br>include Phlex::Rails::Layout<br>def template<br>  doctype<br>  html do<br>   head do<br>    title { yield(:title) }<br>   end<br>   body do<br>    yield<br>   end<br>  end<br> end<br>end</pre><h3>Helpers</h3><h3>Using Rails Helpers</h3><p>Phlex aims to ship with an adapter for every Rails view helper. (Please open an issue if we’re missing one.)</p><p>Each adapter can be included from its own module under Phlex::Rails::Helpers, e.g. Phlex::Rails::Helpers::ContentFor. The module name will match the title-cased method name.</p><p>You can include these adapters as needed, or include the ones you use most commonly in ApplicationComponent or ApplicationView.</p><p>If you need to call the original unadapted helper, you can do that through the helpers proxy. For example, helpers.link_to &quot;Home&quot;, &quot;/&quot; will return the HTML link as a String, while the adapter would output it.</p><h3>Migrating to Phlex</h3><h3>Migrating an existing Rails app to Phlex</h3><p>Whether you currently use ActionView or ViewComponent with ERB, HAML or Slim, you can start using Phlex in your Rails app today without a big rewrite.</p><h3>You can render Phlex views into existing templates</h3><p>Phlex views implement the <em>renderable</em> interface for Rails, which means they can be rendered from a controller or another view template — even ViewComponent templates. This means you can gradually migrate specific views and components to Phlex without having to change everything at once.</p><p>If you’re migrating from ViewComponent, you might find you can convert components to Phlex views without even changing any call-sites.</p><h3>You can render ActionView partials and ViewComponent components in Phlex views</h3><p>The render method in Phlex doesn&#39;t only work with Phlex views. You can use it to render ActionView partials and ViewComponent components.</p><h3>Use an ERB → Phlex converter</h3><p>The ERB → Phlex converter, <a href="https://www.phlexing.fun/">Phlexing</a>, can do the heavy-lifting but it won’t help you architect your components / design system.</p><p>Thank you</p><blockquote>Ashwin Borkar</blockquote><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=5603ab87a4bf" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[[AWS] Experience SQS with AWS SDK for Ruby V2]]></title>
            <link>https://medium.com/@ashwinborkar1997/aws-experience-sqs-with-aws-sdk-for-ruby-v2-446dd5b76323?source=rss-63a18ee16805------2</link>
            <guid isPermaLink="false">https://medium.com/p/446dd5b76323</guid>
            <dc:creator><![CDATA[Ashwin Borkar]]></dc:creator>
            <pubDate>Wed, 07 Feb 2024 07:32:37 GMT</pubDate>
            <atom:updated>2024-02-07T07:32:37.147Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/300/1*CGQ-5sPMEqbjbKXZ7B8FTQ.png" /></figure><h3>Target</h3><p>Build AWS SQS, insert messages into a queue (input from the AWS console), and then retrieve (polling) the inserted messages from EC2 using AWS SDK.</p><h3>What is SQS?</h3><p>A queue service provided by AWS for sending and receiving messages exchanged between applications.<br>This is a pull type service where the receiving side queries SQS for messages and retrieves them.</p><p>I thought that the basic information about SQS was summarized in the following article in an easy-to-understand manner.<br><a href="https://qiita.com/leomaro7/items/296c46ad6366a8dca28c">Amazon SQS</a></p><h3>premise</h3><p>- An EC2 instance that can use the AWS SDK (AWS SDK for Ruby is used in this article) has already been constructed (*).</p><p>*Reference steps when building AWS SDK for Ruby<br><a href="https://qiita.com/aWdfcfG2jLr73pe/items/b784dafd48906c05de23#1aws-sdk-for-ruby%E3%81%AE%E3%82%BB%E3%83%83%E3%83%88%E3%82%A2%E3%83%83%E3%83%97">[AWS SDK] EC2 automatic construction script (1. AWS SDK for Ruby setup)</a></p><h3>Workflow</h3><p>Xiang Fantitle1<a href="https://qiita.com/OPySPGcLYpJE0Tc/items/505be8bf342cb7291a22#1sqs%E3%81%AE%E6%A7%8B%E7%AF%89">Building SQS</a>2<a href="https://qiita.com/OPySPGcLYpJE0Tc/items/505be8bf342cb7291a22#2sqs%E3%81%AB%E3%83%A1%E3%83%83%E3%82%BB%E3%83%BC%E3%82%B8%E3%82%92%E9%80%81%E4%BF%A1">Send message to SQS</a>3<a href="https://qiita.com/OPySPGcLYpJE0Tc/items/505be8bf342cb7291a22#3ec2%E3%81%8B%E3%82%89%E3%83%A1%E3%83%83%E3%82%BB%E3%83%BC%E3%82%B8%E3%82%92%E3%83%9D%E3%83%BC%E3%83%AA%E3%83%B3%E3%82%B0%E3%81%99%E3%82%8B">Poll for messages from EC2</a></p><h3>procedure</h3><h3>1.Building SQS</h3><p><strong>① Open </strong><a href="https://ap-northeast-1.console.aws.amazon.com/sqs/v2/home?region=ap-northeast-1#/"><strong>the SQS console</strong></a></p><p><strong>create queue</strong> <strong>Click ②</strong></p><p><strong>③Setting the queue to be created</strong><br>This time, we will use <strong>the standard queue</strong><br>(*1) Enter any name for the queue.</p><p>*1 SQS has the following two types of queues. Let’s briefly summarize the features.<br>・<strong>Standard queue</strong><br> ⇒ Guarantees message delivery at least once, but depending on the timing of the request, the same message may be delivered multiple times.<br> ⇒The order of message delivery is best effort type (the order of message transmission and delivery may be different.)</p><p>・<strong>FIFO queue</strong><br> ⇒ The same message is never delivered multiple times.<br> ⇒The order of message delivery is first-in, first-out (the order of message transmission and delivery is the same.)<br> ⇒Because it has high performance, it is slightly more expensive than standard queue.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*_zQKmnYhB719h0--" /></figure><p>Configure detailed queue settings (*2).<br>This time, <strong>Message reception waiting time </strong>only set it to 20 seconds, and leave the rest as default.</p><p>*2 Below is a brief description of the detailed settings for the queue.<br>・<strong>Visibility timeout</strong><br>A function that makes the message invisible from other systems for a certain period of time after receiving the message.<br>By completing message processing and deleting the message within the time specified as the visibility timeout,<br>it is possible to prevent the same message from being processed multiple times.</p><p>・<strong>Delivery delay (delay queue)</strong><br>A function that allows the message to be displayed after a specified time has passed after sending the message to the queue.</p><p>・<strong>Message reception waiting time</strong><br>You can set long polling or short polling.<br>The default is short polling (message reception wait time is 0 seconds), and even if the queue is empty, the request will be re-requested immediately.<br>SQS charges are determined by the number of message requests, so if you repeatedly request empty messages, the charges will increase.<br>An effective solution to this problem is long polling (message reception waiting time greater than 0 seconds).<br>When long polling is set, if an empty message is received, it will wait for the specified number of seconds (sustaining the queue connection),<br>reducing the number of SQS requests and saving costs.<br>It depends on your requirements, but AWS seems to basically recommend using long polling.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*VJqalBQ43NCjclqq" /></figure><p>Leave the queue access settings as default.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*VegQ99YiUjL_D1Uz" /></figure><p>Finally, there are settings for encryption, dead letter queue (*3), and tags, but we will not set them this time.<br>Creating a queue Click</p><p>*3 <strong>Dead letter queue</strong><br>A function that automatically moves messages with an error processing result to another queue after retrying several times.<br>Messages with problems are concentrated in another queue, making it easier to identify and confirming that the message is legitimate. prevent it from remaining in the queue.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*wgBt3R5ZW28vy6o1" /></figure><h3>2. Send message to SQS</h3><p>Let’s try sending a message to the created SQS queue from the AWS console.</p><p><strong>Sending and receiving messages</strong> <strong>①Click from the details screen of the SQS queue you created</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*y74IG7GJIOB2i2u5" /></figure><p><strong>Click </strong>Message body <strong>after entering ② </strong>Send Messege<br>Repeat this step several times.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*6xkaGZwctCY9On01" /></figure><p><strong>③ Check the contents of the sent message</strong> Click<br>from the message reception field located at the bottom of the message transmission field <strong>poll for messages</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*8lmBTvRQ7kRapeNs" /></figure><p>It is OK if the message is displayed</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*50BIhbVK31nKCHw9" /></figure><h3>3. Poll for messages from EC2</h3><p><strong>① Deploy the polling execution script to the EC2 instance where AWS SDK for Ruby can be used.</strong></p><pre># **********************************************************************************<br># &lt;機能概要&gt;<br># 指定したSQSキューのメッセージをポーリングする<br>#<br># &lt;機能詳細&gt;<br># 常駐プロセスとして稼働し、指定したSQSキューのメッセージをポーリングし取得時刻及びメッセージ本文を標準出力する。<br># 取得したメッセージは出力後削除する。<br># メッセージが空の場合は指定した時間（wait_time_seconds）分待機した後、キューが空であることを伝えるメッセージを出力する。<br>#<br># &lt;スクリプト用法&gt;<br># ruby &lt;スクリプトパス&gt;<br># **********************************************************************************</pre><pre>require &#39;aws-sdk&#39;</pre><pre># queue name<br>queue_name = &quot;MyTestQueue&quot;</pre><pre># Creating an instance for SQS operations<br>sqs = Aws::SQS::Client.new</pre><pre># Get queue URL<br>begin<br>  queue_url = sqs.get_queue_url(https://medium.com/queue_name:%20queue_name).queue_url<br>rescue Aws::SQS::Errors::NonExistentQueue<br>  puts &quot;A queue named &#39;#{queue_name}&#39; does not exist.&quot;<br>  exit(false)<br>end</pre><pre>loop do<br>  # Get message from queue<br>  receive_message_result = sqs.receive_message({<br>    queue_url: queue_url, <br>    message_attribute_names: [&quot;All&quot;], # Get message with all attributes<br>    max_number_of_messages: 5,        # Get at most 5 messages<br>    wait_time_seconds: 20             # Wait 20 seconds if message is empty<br>  })</pre><pre># Get the time when the message was retrieved<br>  timestamp = Time.new</pre><pre>#Output empty message when message is empty<br>  if receive_message_result.messages.nil?<br>    puts &quot;#{timestamp.strftime(&quot;%Y-%m-%d %H:%M:%S&quot;)}: Message is empty.&quot;<br>  end</pre><pre>receive_message_result.messages.each do |message|<br>    # Display the retrieved message body<br>    puts &quot;#{timestamp.strftime(&quot;%Y-%m-%d %H:%M:%S&quot;)}: #{message.body}&quot;</pre><pre>  # Remove message from queue<br>    sqs.delete_message({<br>      queue_url: queue_url,<br>      receipt_handle: message.receipt_handle    <br>    })<br>  end<br>end</pre><p><strong>② Execute the script and poll for messages.</strong><br>I was able to confirm that the three messages pre-populated from the AWS console were processed immediately, and if the message was empty, it would wait for the specified amount of time.<br>We also confirmed that if we put a new message on the queue while waiting for a message, the message will be processed immediately.</p><pre>[ec2-user@basehost ~]$ ruby queue.rb<br>2020-07-21 04:13:32: test2          #  Message pre-populated from AWS console part 1<br>2020-07-21 04:13:33: test3          # Message pre-populated from the AWS console part 2<br>2020-07-21 04:13:33: test1          #  Message pre-populated from the AWS console Part 3<br>2020-07-21 04:13:53: Message is empty.    # After waiting for the time specified in (20 seconds), output an empty message<br>2020-07-21 04:14:01: This message is the message sent during the waiting time.   # Messages put to the queue during the message waiting time were processed immediately after being put.<br>2020-07-21 04:14:21: Message is empty.<br>2020-07-21 04:14:41: Message is empty.<br>2020-07-21 04:15:01: Message is empty.</pre><h3>[AWS] Experience SQS with AWS SDK for Ruby V2</h3><p>Use AWS SDK for Ruby v2 to sense the SQS queue and write down the code that outputs the message.<br>It has changed quite a bit since V1, so you need to be careful.</p><p>Separate settings are required to set the access key.</p><p>sqs_receive.rb</p><pre>#!/usr/bin/ruby</pre><pre>require &#39;aws-sdk&#39;<br>require &#39;json&#39;</pre><pre># Queue settings<br>queue_url = &quot;https://sqs.ap-northeast-1.amazonaws.com/XXXXX/XXXXX&quot;<br>sqs = Aws::SQS::Client.new(region: &#39;ap-northeast-1&#39;)</pre><pre>loop {<br>    # Get message<br>    msg = sqs.receive_message({<br>        queue_url: queue_url<br>    })</pre><pre>      unless msg.messages[0].nil?<br>        # Display message<br>        result = JSON.parse(msg.messages[0].body)<br>        puts result[&quot;Message&quot;]</pre><pre>        # Delete message<br>        resp = sqs.delete_message({<br>            queue_url: queue_url, # required<br>            receipt_handle: msg.messages[0].receipt_handle # required<br>       })<br>    end</pre><pre>    msg = nil<br>    sleep 10<br>}</pre><p>Thank you 💙</p><p><a href="https://medium.com/u/63a18ee16805">Ashwin Borkar</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=446dd5b76323" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[7 common techniques to improve your debugging skills]]></title>
            <link>https://medium.com/@ashwinborkar1997/7-common-techniques-to-improve-your-debugging-skills-b56da794b15d?source=rss-63a18ee16805------2</link>
            <guid isPermaLink="false">https://medium.com/p/b56da794b15d</guid>
            <dc:creator><![CDATA[Ashwin Borkar]]></dc:creator>
            <pubDate>Mon, 11 Sep 2023 12:26:57 GMT</pubDate>
            <atom:updated>2023-09-11T12:26:57.787Z</atom:updated>
            <content:encoded><![CDATA[<p>When we work on Rails upgrades, most of the time we have to solve issues after updating the gems. These problems can go from simple and straightforward to really complex and hard to debug. Here we will discuss different skills and techniques that we use to complete the upgrade.</p><h3>Basic things which you should always do</h3><ol><li>Ask yourself and others simple or stupid questions. Try to make sure you know what you are fixing.</li><li>Take a close look at an error log or stack trace.</li><li>If you are not sure how or where to start, add debug breakpoints or puts statements in the code. This will help you understand the code workflow.</li><li>Write down your understanding or have a Rubber duck conversation. (The idea is that when a programmer needs to debug their code, they should explain the program line-by-line to a rubber duck. Often, the act of explaining the problem step by step will cause the solution to present itself)</li><li>Pair with someone and discuss your findings.</li><li>Check documentation for the issues you are having.</li><li>Take a break :) and divert your focus temporarily to something else. Then come back and follow the above steps.</li></ol><h3>7 Techniques</h3><p>Most of the techniques here are valid for any Ruby applications, but some are specific to Ruby on Rails applications.</p><p>We will use <a href="https://github.com/fastruby/points">Points opens a new window</a> as an example for all the different techniques we are going to discuss here, so that you can try all these techniques yourself by running the application locally.</p><h3>1. SOURCE_LOCATION - WHERE IS THIS METHOD COMING FROM</h3><p>Sometimes you need to find the source code of a method and it’s not trivial to figure out where it’s defined. Let’s use the <a href="https://github.com/fastruby/points/blob/main/app/controllers/projects_controller.rb#L51">projects_controller opens a new window</a> controller as an example. Imagine we don’t know where clone_params is defined. We can start a debug session right before the method is used and check its source location using the source_location method in the object returned by method(:clone_params):</p><pre>[47, 56] in /Users/myuser/Documents/ombulabs/points/app/controllers/projects_controller.rb<br>  47:   end<br>  48:<br>  49:   def clone<br>  50:     original = Project.includes(stories: :estimates).find(params[:id])<br>  51:     byebug<br>=&gt; 52:     clone = Project.create(clone_params)<br>  53:     original.clone_stories_into(clone)<br>  54:     if clone.parent.nil? &amp;&amp; original.projects<br>  55:       original.clone_projects_into(clone, only: params[:sub_project_ids])<br>  56:     end<br>(byebug) method(:clone_params).source_location<br>[&quot;/Users/myuser/Documents/ombulabs/points/app/controllers/projects_controller.rb&quot;, 118]<br>(byebug) self.method(:clone_params).source_location<br>[&quot;/Users/myuser/Documents/ombulabs/points/app/controllers/projects_controller.rb&quot;, 118]<br>(byebug)</pre><h3>2. GETTING THE CURRENT BACKTRACE</h3><p>There are two ways to get the current backtrace in Ruby:</p><ol><li>Thread.current.backtrace returns the entire backtrace up to and including the current method.</li><li>caller returns the backtrace up to but NOT including the current method.</li></ol><h3>A. CALLER - WHO CALLED THIS METHOD</h3><p>Many times it might be tricky to find the caller of the method. It could be getting called using meta programming, background jobs, controller, gem, engine, callbacks, and more. If you want to find out the caller of the method clone_params, add puts caller in the method to see who is calling it.</p><p>Let’s take this simple method from the <a href="https://github.com/fastruby/points/blob/main/app/controllers/projects_controller.rb#L117">projects_controller.rb opens a new window</a> file:</p><pre>def clone_params<br> puts caller<br> params.require(:project).permit(:title, :parent_id)<br>end<br></pre><pre>OUTPUT &gt;&gt;<br></pre><pre>/Users/myuser/Documents/ombulabs/points/app/controllers/projects_controller.rb:51:in `clone&#39;<br>/Users/myuser/.rbenv/versions/3.2.2/lib/ruby/gems/3.2.0/gems/actionpack-7.0.4.3/lib/action_controller/metal/basic_implicit_render.rb:6:in `send_action&#39;<br>/Users/myuser/.rbenv/versions/3.2.2/lib/ruby/gems/3.2.0/gems/actionpack-7.0.4.3/lib/abstract_controller/base.rb:215:in `process_action&#39;<br>/Users/myuser/.rbenv/versions/3.2.2/lib/ruby/gems/3.2.0/gems/actionpack-7.0.4.3/lib/action_controller/metal/rendering.rb:53:in `process_action&#39;<br>/Users/myuser/.rbenv/versions/3.2.2/lib/ruby/gems/3.2.0/gems/actionpack-7.0.4.3/lib/abstract_controller/callbacks.rb:234:in `block in process_action&#39;<br>/Users/myuser/.rbenv/versions/3.2.2/lib/ruby/gems/3.2.0/gems/activesupport-7.0.4.3/lib/active_support/callbacks.rb:118:in `block in run_callbacks&#39;<br>/Users/myuser/.rbenv/versions/3.2.2/lib/ruby/gems/3.2.0/gems/actiontext-7.0.4.3/lib/action_text/rendering.rb:20:in `with_renderer&#39;<br>/Users/myuser/.rbenv/versions/3.2.2/lib/ruby/gems/3.2.0/gems/actiontext-7.0.4.3/lib/action_text/engine.rb:69:in `block (4 levels) in &lt;class:Engine&gt;&#39;<br>/Users/myuser/.rbenv/versions/3.2.2/lib/ruby/gems/3.2.0/gems/activesupport-7.0.4.3/lib/active_support/callbacks.rb:127:in `instance_exec&#39;</pre><h3>B. THREAD.CURRENT.BACKTRACE</h3><p>This command is helpful when you do not have enough information about the error. Imagine, for example, that you are rescuing an exception when a record is not found. If you want to get more details about the current call stack, you can use Thread.current.backtrace.</p><pre>def find_project<br> begin<br>   @project = Project.find!(params[:project_id])<br> rescue<br>   p Thread.current.backtrace<br> end<br>end<br></pre><pre>OUTPUT &gt;&gt;<br></pre><pre>[&quot;/Users/myuser/Documents/ombulabs/points/app/controllers/projects_controller.rb:113:in `backtrace&#39;&quot;, &quot;/Users/ashwini/Documents/ombulabs/points/app/controllers/projects_controller.rb:113:in `rescue in find_project&#39;&quot;, &quot;/Users/ashwini/Documents/ombulabs/points/app/controllers/projects_controller.rb:109:in `find_project&#39;&quot;, &quot;/Users/ashwini/.rbenv/versions/3.2.2/lib/ruby/gems/3.2.0/gems/activesupport-7.0.4.3/lib/active_support/callbacks.rb:400:in `block in make_lambda&#39;&quot;, &quot;/Users/ashwini/.rbenv/versions/3.2.2/lib/ruby/gems/3.2.0/gems/activesupport-7.0.4.3/lib/active_support/callbacks.rb:180:in `block (2 levels) in halting_and_conditional&#39;&quot;, &quot;/Users/ashwini/.rbenv/versions/3.2.2/lib/ruby/gems/3.2.0/gems/actionpack-7.0.4.3/lib/abstract_controller/callbacks.rb:34:in `block (2 levels) in &lt;module:Callbacks&gt;&#39;&quot;, &quot;/Users/ashwini/.rbenv/versions/3.2.2/lib/ruby/gems/3.2.0/gems/activesupport-7.0.4.3/lib/active_support/callbacks.rb:181:in `block in halting_and_conditional&#39;&quot;, &quot;/Users/ashwini/.rbenv/versions/3.2.2/lib/ruby/gems/3.2.0/gems/activesupport-7.0.4.3/lib/active_support/callbacks.rb:595:in `block in invoke_before&#39;&quot;...]</pre><h3>3. STEP AND NEXT DEBUG METHODS</h3><p>The difference between next and step is that step stops at the next line of code executed, doing just a single step, while next moves to the next line without descending inside methods.</p><p>For example: We want to see what’s happening when we hit the method CSV.parse in our code. Let’s add the debugger before the method call and check. Here you can see how we have used the next and step methods to reach the parse method. We have used step to enter into CSV.parse and then used next to follow through the different calls.</p><pre>[63, 72] in /Users/myuser/Documents/ombulabs/points/app/controllers/stories_controller.rb<br>  63:       flash[:error] = &quot;Invalid File: Must be CSV&quot;<br>  64:       redirect_to(@project) &amp;&amp; return<br>  65:     end<br>  66:     file = begin<br>  67:       byebug<br>=&gt; 68:       CSV.parse(params[:file].read, headers: true)<br>  69:     rescue<br>  70:       []<br>  71:     end<br>  72:     if file.empty?<br>(byebug) step<br></pre><pre>[1220, 1229] in /Users/myuser/.rbenv/versions/3.2.2/lib/ruby/gems/3.2.0/gems/actionpack-7.0.4.3/lib/action_controller/metal/strong_parameters.rb<br>  1220:   # for more information.<br>  1221:   module StrongParameters<br>  1222:     # Returns a new ActionController::Parameters object that<br>  1223:     # has been instantiated with the &lt;tt&gt;request.parameters&lt;/tt&gt;.<br>  1224:     def params<br>=&gt; 1225:       @_params ||= begin<br>  1226:         context = {<br>  1227:           controller: self.class.name,<br>  1228:           action: action_name,<br>  1229:           request: request,<br>(byebug) next<br></pre><pre>[639, 648] in /Users/myuser/.rbenv/versions/3.2.2/lib/ruby/gems/3.2.0/gems/actionpack-7.0.4.3/lib/action_controller/metal/strong_parameters.rb<br>  639:     #<br>  640:     #   params = ActionController::Parameters.new(person: { name: &quot;Francesco&quot; })<br>  641:     #   params[:person] # =&gt; #&lt;ActionController::Parameters {&quot;name&quot;=&gt;&quot;Francesco&quot;} permitted: false&gt;<br>  642:     #   params[:none]   # =&gt; nil<br>  643:     def [](key)<br>=&gt; 644:       convert_hashes_to_parameters(key, @parameters[key])<br>  645:     end<br>  646:<br>  647:     # Assigns a value to a given +key+. The given key may still get filtered out<br>  648:     # when +permit+ is called.<br>(byebug) next<br></pre><pre>[44, 53] in /Users/myuser/.rbenv/versions/3.2.2/lib/ruby/gems/3.2.0/gems/actionpack-7.0.4.3/lib/action_dispatch/http/upload.rb<br>  44:         @headers           = hash[:head]<br>  45:       end<br>  46:<br>  47:       # Shortcut for +tempfile.read+.<br>  48:       def read(length = nil, buffer = nil)<br>=&gt; 49:         @tempfile.read(length, buffer)<br>  50:       end<br>  51:<br>  52:       # Shortcut for +tempfile.open+.<br>  53:       def open<br>(byebug) next<br></pre><pre>[1727, 1736] in /Users/myuser/.rbenv/versions/3.2.2/lib/ruby/3.2.0/csv.rb<br>  1727:     #<br>  1728:     # Raises an exception if the argument is not a \String object or \IO object:<br>  1729:     #   # Raises NoMethodError (undefined method `close&#39; for :foo:Symbol)<br>  1730:     #   CSV.parse(:foo)<br>  1731:     def parse(str, **options, &amp;block)<br>=&gt; 1732:       csv = new(str, **options)<br>  1733:<br>  1734:       return csv.each(&amp;block) if block_given?<br>  1735:<br>  1736:       # slurp contents, if no block is given<br>(byebug) next<br></pre><pre>[1729, 1738] in /Users/myuser/.rbenv/versions/3.2.2/lib/ruby/3.2.0/csv.rb<br>  1729:     #   # Raises NoMethodError (undefined method `close&#39; for :foo:Symbol)<br>  1730:     #   CSV.parse(:foo)<br>  1731:     def parse(str, **options, &amp;block)<br>  1732:       csv = new(str, **options)<br>  1733:<br>=&gt; 1734:       return csv.each(&amp;block) if block_given?<br>  1735:<br>  1736:       # slurp contents, if no block is given<br>  1737:       begin<br>  1738:         csv.read</pre><h3>4. MONKEY PATCHING</h3><p>Did you know that you can open any class in Ruby and modify it? Yes, we can open any class of any gem or library to debug.</p><p>In the previous example, we showed you how to get into the CSV.parse method using next/step, but if you want to avoid those steps (sometimes there can be many method calls in between) you can open the CSV class and modify it.</p><p>Let’s see how.</p><p>Imagine you have a problem when parsing the imported CSV file in <a href="https://github.com/fastruby/points/blob/main/app/controllers/stories_controller.rb#L67">this controller action. opens a new window</a></p><p>Let’s start finding out where the CSV.parse method is defined. Add a byebug call and then use source_location.</p><pre>(byebug)  CSV.method(:parse).source_location<br>[&quot;/Users/myuser/.rbenv/versions/3.2.2/lib/ruby/3.2.0/csv.rb&quot;, 1731]</pre><p>We can monkeypatch the parse class method of the CSV module like this:</p><p>Take the code from <a href="https://github.com/ruby/ruby/blob/v3_2_2/lib/csv.rb#L1731">csv.rb opens a new window</a>, create a file in your lib folder with the name, let’s say, csv.rb, and paste the following code in it. Now you can debug Ruby’s CSV.parse method, check different params, etc.</p><pre>class CSV<br> def self.parse(str, **options, &amp;block)<br>   byebug<br>   csv = new(str, **options)<br>return csv.each(&amp;block) if block_given?<br><br>   # slurp contents, if no block is given<br>   begin<br>     csv.read<br>   ensure<br>     csv.close<br>   end<br> end<br>end</pre><h3>5. METHODS.GREP TO SEARCH FOR A METHOD IN AN OBJECT</h3><p>Sometimes you want to check if an object has a particular method but you don’t know the exact method name, only part of it. You can use the grep command and search for the method you want using a regular expression.</p><p>For example, given an object instance of the Project class, what are the different methods related to stories:</p><pre>(byebug) Project.new.methods.grep /stories/<br>[:clone_stories_into, :autosave_associated_records_for_stories, :validate_associated_records_for_stories, :stories, :stories=]</pre><h3>6.TO_SQL TO SEE WHAT QUERY ACTIVERECORD WILL GENERATE</h3><p>Sometimes it is hard to understand complex joins between different models. Or maybe you are not getting the result you are expecting. In such cases, it is always a good idea to see what the plain SQL query ActiveRecord is generating looks like. to_sql will print out the full query.</p><pre>(byebug) Project.joins(:stories).where(stories: { title: &quot;Story #0&quot;}).to_sql<br>&quot;SELECT \&quot;projects\&quot;.* FROM \&quot;projects\&quot; INNER JOIN \&quot;stories\&quot; ON \&quot;stories\&quot;.\&quot;project_id\&quot; = \&quot;projects\&quot;.\&quot;id\&quot; WHERE \&quot;stories\&quot;.\&quot;title\&quot; = &#39;Story #0&#39;&quot;</pre><h3>7. RELOAD ACTIVERECORD OBJECTS</h3><p>Sometimes you save an ActiveRecord object in one place and you still see the old attributes in another place. Try reloading that object to make sure that the record in memory is in sync with the database. The reload method is defined by ActiveRecord; it can be used in any object instance of the ActiveRecord::Base class.</p><p>These are 7 strategies you can use to debug Rails applications. There are some more strategies explained in <a href="https://guides.rubyonrails.org/debugging_rails_applications.html">this Rails Guide opens a new window</a>.</p><p>Thank you !</p><p><a href="https://medium.com/u/63a18ee16805">Ashwin Borkar</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b56da794b15d" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>