<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0" xmlns:atom="http://www.w3.org/2005/Atom" xmlns:dc="http://purl.org/dc/elements/1.1/">
  <channel>
    <title>DEV Community: Deepak Singh</title>
    <description>The latest articles on DEV Community by Deepak Singh (@__deepak__).</description>
    <link>https://dev.to/__deepak__</link>
    <image>
      <url>https://media2.dev.to/dynamic/image/width=90,height=90,fit=cover,gravity=auto,format=auto/https:%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Fuser%2Fprofile_image%2F77773%2F317fd437-ae56-439a-88e5-cf88044736f8.jpg</url>
      <title>DEV Community: Deepak Singh</title>
      <link>https://dev.to/__deepak__</link>
    </image>
    <atom:link rel="self" type="application/rss+xml" href="https://dev.to/feed/__deepak__"/>
    <language>en</language>
    <item>
      <title>Rails Action Pack Variants</title>
      <dc:creator>Deepak Singh</dc:creator>
      <pubDate>Mon, 06 Aug 2018 16:43:56 +0000</pubDate>
      <link>https://dev.to/__deepak__/rails-action-pack-variants-1lc3</link>
      <guid>https://dev.to/__deepak__/rails-action-pack-variants-1lc3</guid>
      <description>&lt;p&gt;Recently on one of the projects at &lt;a href="https://eloquent.studio" rel="noopener noreferrer"&gt;Eloquent Studio&lt;/a&gt;, I needed to render two very different view templates for desktop and mobile, even Bootstrap responsive design did not fit the requirement.&lt;/p&gt;

&lt;p&gt;A little hesitant to roll out a custom solution for such a common requirement, I did some google searches and struck up the RailsGuides. &lt;code&gt;ActionPack Variants&lt;/code&gt; is just what I was looking for. &lt;code&gt;ActionPack Variants&lt;/code&gt; is a specialisation of &lt;code&gt;request format&lt;/code&gt;. Released with Rails 4.1, the api was later improved to its current state in Rails 5 as per this &lt;a href="https://github.com/rails/rails/pull/18939" rel="noopener noreferrer"&gt;PR&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;Within the controller action's respond to block&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;# app/controllers/patterns_controller.rb
before_action :set_variant, only: :show

def show
  format.html do |html|
    html.phone
    html.tablet
  end
end

private

def set_variant
  case request.user_agent
    when /iPad/i
      request.variant = :tablet
    when /iPhone/i
      request.variant = :phone
    when /Android/i &amp;amp;&amp;amp; /mobile/i
      request.variant = :phone
    when /Android/i
      request.variant = :tablet
    when /Windows Phone/i
      request.variant = :phone
  end
end
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;And setup view templates as&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;# app/views/patterns/show.html.erb

# Show page for desktop view
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;





&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;# app/views/patterns/show.html+tablet.erb

# Show page for tablet view
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;





&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;# app/views/patterns/show.html+phone.erb

# Show page for phone view
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Not just devices, variants can be used for more varied use cases, like rendering different view templates based on user roles.&lt;/p&gt;

&lt;p&gt;CoverImage Credits: &lt;a href="https://unsplash.com/@bugsster" rel="noopener noreferrer"&gt;https://unsplash.com/@bugsster&lt;/a&gt;&lt;/p&gt;

</description>
      <category>rails</category>
      <category>actionpack</category>
      <category>variants</category>
    </item>
    <item>
      <title>Clean Validations with Custom Contexts</title>
      <dc:creator>Deepak Singh</dc:creator>
      <pubDate>Wed, 01 Aug 2018 10:29:50 +0000</pubDate>
      <link>https://dev.to/__deepak__/clean-validations-with-custom-contexts-2pci</link>
      <guid>https://dev.to/__deepak__/clean-validations-with-custom-contexts-2pci</guid>
      <description>&lt;p&gt;Active Record validations are a well-known and widely used in Rails.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;class User &amp;lt; ApplicationRecord
  validates :name, presence: { message: "must be given please" }
end
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;This runs the validation on &lt;code&gt;save&lt;/code&gt;, both when creating a new record or when updating an existing record.&lt;/p&gt;

&lt;p&gt;&lt;code&gt;on&lt;/code&gt; option allows control over when to run the validation, commonly used with value of &lt;code&gt;create&lt;/code&gt; or &lt;code&gt;update&lt;/code&gt;&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;class User &amp;lt; ApplicationRecord
  belongs_to :club, optional: true 
  validates :name, presence: { message: "must be given please" }, on: :create
  validates :club, presence: { message: "must be given please" }, on: :update  
end
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;This allows creating users without associating them with a Club, but enforces presence of Club on subsequent updates. This pattern is commonly used to allow users to signup with bare minimum form fields and then forcing them to update their profiles with more information on subsequent visits.&lt;/p&gt;

&lt;p&gt;Value for the &lt;code&gt;on&lt;/code&gt; option is not limited to &lt;code&gt;create&lt;/code&gt; and &lt;code&gt;update&lt;/code&gt;, we can have our own custom contexts. Like in a multistep form, we can have validations for each of the steps. &lt;code&gt;on&lt;/code&gt; options makes this really easy to do&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;class User &amp;lt; ApplicationRecord
  validate :basic_info, on: :basic_info
  validate :education_details, on: :education_details
  validate :professional_info, on: :professional_info

  private
  def basic_info
    # Validation for basic info, first_name, last_name, email
  end

  def education_details
    # Validation for education_details
  end

  def professional_info
    # Validation for professional_info
  end
end
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;In the controller&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;class UsersController &amp;lt; ApplicationController
  ...

  def update_basic_info
    @user.assign_attributes(basic_info_params)
    @user.save(:basic_info)
  end

  def update_education_details
    @user.assign_attributes(education_details_params)
    @user.save(:education_details)
  end

  def update_professional_info
    @user.assign_attributes(professional_info_params)
    @user.save(:professional_info)
  end

  private
  def basic_info_params
    # strong params
  end

  def education_details_params
    # strong params
  end

  def professional_info_params
    # strong params
  end
end
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;With Rails 5  adding support for multiple contexts, we can use multiple context together&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;@user.save(:basic_info, :professional_info)
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;This seems pretty neat, let's go a step further and do this with &lt;code&gt;update_attributes&lt;/code&gt;. In current implementation of Rails,&lt;br&gt;
&lt;code&gt;update_attributes&lt;/code&gt; does not support validation contexts. We can get around this by defining our own custom method&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;class ApplicationRecord &amp;lt; ActiveRecord::Base
  self.abstract_class = true

  def update_attibutes_with_context(attributes, *contexts)
    with_transaction_returning_status do
      assign_attributes(attributes)
      save(context: contexts)
    end
  end
end
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;In the controller&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;@user.update_attibutes_with_context({first_name: 'fname'}, :basic_info)
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Lastly, we can use &lt;code&gt;with_options&lt;/code&gt; to group multiple validation within a context&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;  with_options on: :member do |member_user|
    member_user.validates :club_name, presence: true
    member_user.validates :membership_id, presence: true
  end
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;This makes really easy to write readable and maintainable code, with a good separation of concerns.&lt;/p&gt;

&lt;p&gt;Read my last post on ActiveRecord Validations here &lt;a href="https://dev.to/spidergears/rails-active-record-validation-messages-4dcf"&gt;https://dev.to/spidergears/rails-active-record-validation-messages-4dcf&lt;/a&gt;&lt;/p&gt;

</description>
      <category>rails</category>
      <category>activerecord</category>
      <category>validations</category>
      <category>context</category>
    </item>
    <item>
      <title>Better Rails Active Record Validation Messages</title>
      <dc:creator>Deepak Singh</dc:creator>
      <pubDate>Tue, 17 Jul 2018 22:07:06 +0000</pubDate>
      <link>https://dev.to/spidergears/rails-active-record-validation-messages-4dcf</link>
      <guid>https://dev.to/spidergears/rails-active-record-validation-messages-4dcf</guid>
      <description>&lt;p&gt;Validations are used to ensure that only valid data is saved to database and no business rules are violated. For example, it may be important for business to ensure that users provides a valid email address and phone number. Model-level validations are the most common way (db-level constraints is another option) to achieve this. Model-level validations are database agnostic, simple to test and maintain. Rails makes this more fun with built-in helpers and support for custom validations.&lt;/p&gt;

&lt;p&gt;All that being done, the next crucial step is to provide users with immediate feedback as they use your site. Rails allows to do just that with the &lt;code&gt;:message&lt;/code&gt; option. It specifies the customised error message that will be added to the errors collection when the validation fails.&lt;/p&gt;

&lt;p&gt;The &lt;code&gt;:message&lt;/code&gt; option accepts a &lt;code&gt;string&lt;/code&gt; or a &lt;code&gt;proc&lt;/code&gt;.&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;When using strings, rails provides placeholder/interpolation variables to help add context and reduce cognitive load.

&lt;ul&gt;
&lt;li&gt;%{value}&lt;/li&gt;
&lt;li&gt;%{attribute}&lt;/li&gt;
&lt;li&gt;%{model}
Use them in the message string as,
&lt;/li&gt;
&lt;/ul&gt;


&lt;/li&gt;

&lt;/ul&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;validates :age, numericality: { message: "%{attribute} must be a number" }
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;code&gt;Age must be a number&lt;/code&gt; feels much better than &lt;code&gt;must be a number&lt;/code&gt;.&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;Using procs adds more flexibility and logic to the message string. Proc has access to the object being validated and a data hash with keys &lt;code&gt;model&lt;/code&gt;, &lt;code&gt;attribute&lt;/code&gt; and &lt;code&gt;value&lt;/code&gt;, same as the interpolation variable above.
&lt;/li&gt;
&lt;/ul&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;validates :username,
    uniqueness: {
      message: -&amp;gt;(object, data) do
        "Hey #{object.name}!, #{data[:value]} is taken already!"
      end
    }
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;





&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;validates :score,
    presence: {
      message: -&amp;gt;(object, data) do
        if object.member?
          "something"
        else
          "Something else"
        end    
      end
    }
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Magic does not end here, rails also allows overriding default validation messages via i18n-localization files.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;en:
  activerecord:
    errors:
      models:
        user:
          attributes:
            firstname:
              blank: "custom message, can\'t be blank"

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;a href="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2F12xtfzcepxgywdwtlpiv.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2F12xtfzcepxgywdwtlpiv.png" alt="Presence validation error on firstname"&gt;&lt;/a&gt;&lt;br&gt;
Active Record provides couple of namespaces where message translations can be placed in order to provide different messages and translation for certain models, attributes, and/or validations. It also transparently takes single table inheritance into account.&lt;/p&gt;

&lt;p&gt;Also placeholder/interpolation variables are still available.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;en:
  activerecord:
    errors:
      models:
        user:
          attributes:
            firstname:
              blank: "Please fill in your %{attribute}"
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;a href="http://guides.rubyonrails.org/i18n.html#translations-for-active-record-models" rel="noopener noreferrer"&gt;http://guides.rubyonrails.org&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;Further, ActiveModel::Errors#full_messages prepends the attribute name to the error message using a separator that is looked up from &lt;code&gt;errors.format&lt;/code&gt; (and defaults to &lt;code&gt;%{attribute} %{message}&lt;/code&gt;). This too can be customised as&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;en:
  errors:
    # format to use in full error messages.
    format: "%{message} %{attribute}"
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



</description>
      <category>rails</category>
      <category>activerecord</category>
      <category>validations</category>
      <category>errormessages</category>
    </item>
    <item>
      <title>Dev.pun</title>
      <dc:creator>Deepak Singh</dc:creator>
      <pubDate>Thu, 28 Jun 2018 16:00:37 +0000</pubDate>
      <link>https://dev.to/spidergears/devpun-3o44</link>
      <guid>https://dev.to/spidergears/devpun-3o44</guid>
      <description>&lt;p&gt;&lt;a href="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fthepracticaldev.s3.amazonaws.com%2Fi%2Fhac86s6t4ceralnr6ibb.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fthepracticaldev.s3.amazonaws.com%2Fi%2Fhac86s6t4ceralnr6ibb.png" alt="dev.pun"&gt;&lt;/a&gt;&lt;/p&gt;

</description>
      <category>devpun</category>
      <category>isthisfunny</category>
      <category>meta</category>
    </item>
    <item>
      <title>Code for Humans</title>
      <dc:creator>Deepak Singh</dc:creator>
      <pubDate>Fri, 22 Jun 2018 13:10:09 +0000</pubDate>
      <link>https://dev.to/spidergears/code-forhumans-2c4h</link>
      <guid>https://dev.to/spidergears/code-forhumans-2c4h</guid>
      <description>&lt;h6&gt;
  
  
  white-spaces are code too...
&lt;/h6&gt;

&lt;p&gt;It's great, your code works in production and is fast enough.&lt;br&gt;
Congratulation, but...&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;Is it readable enough?&lt;/li&gt;
&lt;li&gt;How easy is it for a new developer to pick it up and make all the sense?&lt;/li&gt;
&lt;li&gt;Does reading through the code present a good mental model of the system built?&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;This not an exhaustive list, but if answer to any of the above question is NO, then  you should consider revisiting and making a few cosmetic changes.&lt;/p&gt;

&lt;p&gt;Here are a few pointers that I follow when writing/reading code&lt;/p&gt;

&lt;h4&gt;
  
  
  white-spaces
&lt;/h4&gt;


&lt;div class="highlight"&gt;&lt;pre class="highlight plaintext"&gt;&lt;code&gt;- white-spaces are code too

&lt;ul&gt;
&lt;li&gt;leave a blank line between method definitions&lt;/li&gt;
&lt;li&gt;a blank line when there is a changes in context within method body 
&lt;/li&gt;
&lt;/ul&gt;&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;
&lt;h4&gt;


indentation
&lt;/h4&gt;
&lt;div class="highlight"&gt;&lt;pre class="highlight plaintext"&gt;&lt;code&gt;- indent code well
&lt;li&gt;follow consistent indent length, 2 spaces or 4 spaces&lt;/li&gt;
&lt;li&gt;be consistent with use of tabs or spaces, choose one and stick to it across the team(s)
&lt;/li&gt;&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;
&lt;h4&gt;


variable and method naming
&lt;/h4&gt;
&lt;div class="highlight"&gt;&lt;pre class="highlight plaintext"&gt;&lt;code&gt;- use concise and meaningful names
&lt;li&gt;variable names should reflect the value they refer&lt;/li&gt;
&lt;li&gt;method names should reflect the process / business logic contained
&lt;/li&gt;&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;
&lt;h4&gt;


documentation
&lt;/h4&gt;
&lt;div class="highlight"&gt;&lt;pre class="highlight plaintext"&gt;&lt;code&gt;- unless it is a framework, module, class, method, variable names should be self documenting without need of additional documentation
&lt;li&gt;comments should not be a tool to justify messy code segments
&lt;/li&gt;&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;
&lt;h4&gt;


design the code
&lt;/h4&gt;
&lt;div class="highlight"&gt;&lt;pre class="highlight plaintext"&gt;&lt;code&gt;- every code is a piece of art uniquely conceived by it's developer
&lt;li&gt;visualise the interactions between objects before beginning to code&lt;/li&gt;
&lt;li&gt;visualise message exchanges needed before beginning to code
&lt;/li&gt;&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;
&lt;h4&gt;


right abstraction
&lt;/h4&gt;
&lt;div class="highlight"&gt;&lt;pre class="highlight plaintext"&gt;&lt;code&gt;- abstraction does not mean hiding the complexity detail
&lt;li&gt;know the behavioural traits to model&lt;/li&gt;
&lt;li&gt;have a api spec to refer to&lt;/li&gt;
&lt;li&gt;know before hand methods, variables, constants to expose&lt;/li&gt;
&lt;li&gt;do not make decisions based on speculations&lt;/li&gt;
&lt;li&gt;requirements are the corner stone
&lt;/li&gt;&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;
&lt;h4&gt;


language idioms
&lt;/h4&gt;
&lt;div class="highlight"&gt;&lt;pre class="highlight plaintext"&gt;&lt;code&gt;- make use of language idioms
&lt;li&gt;Ruby Example: [1, 2, 3, 4].sum  v/s  [1, 2, 3, 4].each {|ele| sum = sum + ele}
&lt;/li&gt;&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;
&lt;h2&gt;


Code for Humans
&lt;/h2&gt;


&lt;p&gt;&lt;small&gt;Cover Image Credit: &lt;a href="https://unsplash.com/photos/cvBBO4PzWPg"&gt;Unsplash&lt;/a&gt;&lt;/small&gt;&lt;/p&gt;

</description>
      <category>code</category>
      <category>humans</category>
      <category>codequality</category>
      <category>readability</category>
    </item>
    <item>
      <title>Dev.to tech-stack</title>
      <dc:creator>Deepak Singh</dc:creator>
      <pubDate>Fri, 22 Jun 2018 07:50:44 +0000</pubDate>
      <link>https://dev.to/__deepak__/devto-tech-stack-3pbn</link>
      <guid>https://dev.to/__deepak__/devto-tech-stack-3pbn</guid>
      <description>&lt;p&gt;I was initially drawn to dev.to after reading a &lt;del&gt;medium&lt;/del&gt; dev.to article about how fast the platform is. I would like to know more on the architecture and infrastructure involved, helping dev.to stay up everyday. &lt;/p&gt;

</description>
      <category>discuss</category>
    </item>
  </channel>
</rss>
