Rate limiting examples 🙌🏼 With Rails 8 upgrade, developers can now leverage built-in rate-limiting controls directly within their controllers 🚀 Advantages Prevents Abuse: Rate limiting deters spamming, brute-force attacks, and abusive behavior by controlling request frequency. Enhances Security: By limiting requests, it reduces vulnerability to denial-of-service (DoS) attacks. Improves…
Clear development log while start server 🗑 Do you find yourself manually clearing your Rails development logs often? or forgot to do so and it results in having file-size is greater than 1000 MB 😕 Here’s a simple solution to automate the process! Create an initializer file under config/initializers and add the following code: # config/initializers/clear_development_log.rb if…
Passing argument with Array#first and Array#last Methods Did you know that you can pass an argument to the Array#first and Array#last methods to return a specific number of elements from the beginning or end of the array? The Array#first method returns the first element of the array, or the first n elements if an argument is provided. For example: ❯ array = [1, 2, 3, 4, 5] ❯ array.
A better way to Convert a URL Query String to a Hash ✨ In Ruby on Rails, you might need to work with URL query strings when building web applications that interact with external APIs or handle user input. When working with a URL that contains a query string, you can use Ruby’s URI and Rack::Utils modules to extract parameters and store them in a hash. Here’s an example of how to…
Validate keys of hash using `assert_valid_keys` 🚧 Have you heard of the assert_valid_keys method for the Hash class in Rails? This method provides an easy way to validate the keys of a hash against a list of expected keys. It raises an error if the hash contains any keys that are not included in the expected list. This is useful for ensuring that only valid parameters are passed to methods and…
Using `pluck` instead of `all` Instead of using the all method, which loads all records into memory, use the pluck method to retrieve specific columns from the database. For example, if you only need to retrieve the names/emails of all users, you can use the following code: # Using pluck instead of all ❯ user_names = User.pluck(:name) ❯ user_emails = User.pluck(:email) This will return an array of…
Use render with `respond_to` You can use the render method to display content in a different format such as JSON or XML. This can be useful when working with APIs. For example, to render a JSON response, you can add the following code to your controller action: def show respond_to do |format| format.html # show.html.erb format.json { render :json => @post } end end In this example, if the request…
Difference between `to_s` and `to_str` 🙌🏼 Let’s take an example of to_s and to_str here. Both are used to transform a value from one type to another. We usually use to_s to convert an object into string while to_str allows you to verify that the object can be considered as string. Code Snippet - # String ❯ "Ruby".to_s #=> "Ruby" ❯ "Ruby".respond_to?(:to_str) #=> true ❯ "Ruby".to_str #=>…
Numerical validation using `validates_comparison_of` 🙌🏼 Do you know you can use validates_comparison_of with Rails 7.0 that provides a way to easily validate comparisons with another value, proc, or attribute? There are multiple helpers available - 1. greater_than 2. less_than 3. greater_than_or_equal_to 4. less_than_or_equal_to 5. equal_to 6. other_than It works with - 1. Numeric Values 2.…
Usage of invert_where for inverting entire where clause 🙌🏼 With Rails 7.0, you can use invert_where to invert an entire where clause instead of manually applying conditions 💣 Reference - Rails PR #40249 Code snippet 📌 # Version: Rails 7.0 class User scope :active, -> { where(is_active: true) } end # Before active_users = User.active inactive_users = User.where(active: false) # After…
Usage of authenticate_by for preventing timing-based enum attacks ⏳ 🙌🏼 Add authenticate_by when using has_secure_password. authenticate_by is intended to replace code like the following, which returns early when a user with a matching email is not found: User.find_by(email: "...")&.authenticate("...") Such code is vulnerable to timing-based enumeration attacks, wherein an attacker can determine…
Freezing string to improve performance 🙌🏼 Advantage - If you freeze string object, it’ll not allocate new memory and it improves app performance by saving time for garbage collection 🔥 Reference - Ruby Optimization with One Magic Comment Code snippet 📌 def get_object_id object = 'Ruby' object.object_id end puts get_object_id #=> 70106567869780 puts get_object_id #=> 70106566368140 # Add…
Always use is_a? or kind_of? over instance_of? 🙌🏼 While all three methods looks similar, is_a? or kind_of? will consider the whole inheritance chain (superclasses and included modules), which is what you normally would want to do. instance_of?, on the other hand, only returns true if an object is an instance of that exact class you’re checking for, not a subclass. Reference - Ruby Style Guide…
Use of xxx_changed? and xxx_was methods in Rails 🙌🏼 In Ruby/Rails, while you modify any attribute and compare it in observer, instead of using changes method you can use xxx_changed? and xxx_was methods. Code snippet 📌 user = User.create(name: "Rishi", is_active: false) user.is_active = true # Comparing using changes method if user.changes.present? && user.changes[:is_active].present? &&…
values_at method to retrieve multiple non-sequential values 🙌🏼 Do you know you can use values_at to retrieve multiple non-sequential values from array or hash? Code snippet 📌 # For a given array it will return an array of the values associated with the index position. ❯ directions = [ 'North', 'East', 'West', 'South' ] ❯ directions.values_at(0, 2) ❯ ["North", "West"] # For a given hash it will…
Using underscore to make large number more readable ⚡️ Do you know we can use underscore to make large number more readable in ruby? 🤔 Code Snippet - large_number = 1000000 # More Readable large_number = 10_00_000
Numerical comparison using `range` and `between` 😊 Do you know we can use range or between to do numerical comparison in ruby? 🤔 Code Snippet - do_something if x >= 100 && x <= 200 # Use Range do_something if (100..200).include?(x) # Use between do_something if x.between?(100, 200)
Different ways to call a method in Ruby! wanted to know different ways to call a method in ruby? 🤔 Check this out - class MyClass def method_name puts "Public method inside MyClass" end end ❯ MyClass.new.method_name ❯ MyClass.new::method_name ❯ MyClass::new::method_name ❯ MyClass.new.send(:method_name) # work with private methods ❯ MyClass.new.method(:method_name).call ❯…
Customize default getter/setter methods(attr_accessor) ✌🏼 Wanted to customize default getter/setter methods available in ruby called attr_accessor? 🤔 Check this out - class User # Defining custom attribut accessor def self.custom_attr_accessor(*attrs) attrs.each do |attr| attr_name = "@#{attr}".to_sym # custom getter(custom code for modifying output) define_method attr do…
Recently, the Indian govt announced vaccination for 18-45 age group from 1st May ✨ Anyone who wants to vaccinate in this age group can visit official website or install Arogya Setu App from Google Play to book a slot for vaccination. The problem is vaccination is limited and slots are also limited, so whenever anyone wanted to book a slot, it always shows booked on official website 😢 After…
Symbols can best be described as identities. A symbol is all about who it is, not what it is 🙌🏼 The object_id method returns the identity of an Object. If two objects have the same object_id, they are the same (point to the same Object in memory). Symbol with the same characters references the same Object in memory, and in case of String they’re referencing two different objects in memory.
Use customized starting index with each_with_index while using Enumerator 🙌🏼 In your Ruby on Rails project, you can use each.with_index(starting-index) instead of each_with_index if you wanted to customize starting index of enumerator(Array) Code snippet 📌 # Normal loop over enumerator ('a'..'e').each_with_index do |k,i| puts "#{k} - #{i}" end # Output a - 0 b - 1 c - 2 d - 3 e - 4 # Loop with…
𝗥𝘂𝗯𝘆 𝟯.𝟬 is released and here are list of improvements ⚡️ 📌 In some benchmarks Ruby3.0 is three times faster than Ruby2.0 📌 Lot many performance improvements in Method Based Just-in-Time Compiler 📌 With Ractor, along with Async Fiber, Ruby will be a real concurrent language 📌 Light-weight concurrency without changing existing code using Fiber#scheduler 📌 Ships with RBS Gem, which allows…
Easy way to clean Sidekiq Jobs Cheat-Sheet 💣 Easy way to clean Sidekiq Jobs Cheat-Sheet 💣 Code snippet 📌 ❯ require 'sidekiq/api' # Clear retry set ❯ Sidekiq::RetrySet.new.clear # Clear scheduled jobs ❯ Sidekiq::ScheduledSet.new.clear # Clear 'Dead' jobs ❯ Sidekiq::DeadSet.new.clear # Clear 'Processed' and 'Failed' jobs ❯ Sidekiq::Stats.new.reset # Clear 'Dead' jobs statistics ❯…
Image from Unsplash There are certain characteristics that differentiate great developers from good developers. And it goes beyond what they know. It takes TIME, PATIENCE and Perseverance to become great at anything. Here are few ways which will help you to become a great developer - 1. Before start coding, clear requirements, clear doubts & write pseudocode 🤔 2. Get yourself good at Google…
Array operations in Ruby 🗄 Easy way to get the intersection, union, and subset of arrays in Ruby 👇🏼 Code snippet 📌 x = [1, 1, 2, 4] y = [1, 2, 2, 2] # intersection x & y # => [1, 2] # union x | y # => [1, 2, 4] # difference x - y # => [4]
Handy numerical methods 🔖 Handy numerical methods you can use on daily basis in comparison statements in Ruby 🧮 Code snippet 📌 ❯ num = 10 ❯ num.even? # same as num % 2 == 0 ❯ true ❯ num.odd? # same as num % 2 != 0 ❯ false ❯ num.positive? # same as num > 0 ❯ true ❯ num.negative? # same as num < 0 ❯ false ❯ num.
Image from unsplash.com I’ve been nominated in the 2020 #Noonies, Hacker Noon’s annual awards! 🎉 The Noonies are HackerNoon’s way of recognizing the tech industry’s top writers, thinkers, leaders, and makers (more info here) I've been nominated as "Ruby on Rails Thinker of the Year" in the @hackernoon Noonies 🎉 If you find my #RailsTips useful, I would be really grateful if you can vote for me…
List all TODO tasks from Ruby on Rails Project 🔖 To get all # TODO tasks from your Ruby on Rails project you can use rake notes It’ll search for comments beginning with a specific keyword and also give filename and line 📋 Code snippet 📌 # list down all comments starts with # TODO, # FIXME & # OPTIMIZE ❯ rake notes app/controliers/admin/users_controller.rb: * [ 20] [TODO] any other way to…
Better way to write website(URL) Validation ✨ Use URI::regexp(%w(http https)) in your Ruby on Rails model, to increase readability of website(URL) validation. Code snippet 📌 # website URL validation validates :website, format: { with: /((?:(http|https)?\:\/\/|www\.)(?:[-a-z0-9]+\.)*[-a-z0-9]+.*)/i } # can be write as validates :website, format: { with: URI::regexp(%w(http https)) }
Like operator in MongoDB 🧩 A good way to use operator LIKE in Ruby on Rails while using MongoDB 💡 Code snippet 📌 # app/models/mongoid/base_model.rb module Mongoid module BaseModel extend ActiveSupport::Concern module ClassMethods def _search_(k, v) if k && v && v.size > 0 any_of({ k => /.*#{v}.*/i }) else all end end alias method :like, :_search_ end end end # app/models/lead.rb class Lead…
Better way to split an array using Partition ⛓ Imagine you could, in one line, split an array into two arrays based on a condition 🤔 Now stop imagining, you can do exactly that with partition 🤩 Code snippet 📌 # ok: let's split an array to an odd array and even array def split_odds_evens(nums) odds = [] evens = [] nums.each do |num| if num.odd? odds << num else evens << num end end [odds, evens]…
Safe Navigation Operator (&.) A good way to use safe navigation operator (&.) in your code ✨ Code snippet 📌 if client.present? && client.address.present? @city = client.address.city end # with safe navigation operator (&.) @city = client&.address&.city Read more 🔖 - http://mitrev.net/ruby/2015/11/13/the-operator-in-ruby/
Better way to write Email Validation ✨ Use URI::MailTo::EMAIL_REGEXP in your Ruby on Rails model, to increase readability of email validation. Code snippet 📌 Email validation - validates email, format: { with: AA([a-zA-Z0-9_.+-]+)@((?:[-a-z0-9]+\.)+[a-z]{2,})\z/i } Can be write as - validates format: { with: URI::MailTo::EMAIL_REGEXP }
Convert Array of Hashes to Hash! In your Ruby on Rails project, you can override array.rb file and add few good methods there 🍀 i.e. - convert array of hashes to hash. Path - lib/array.rb ⚠️ Don’t forget to require it in application.rb Code snippet 📌 def convert_to_hash Hash[self.map(&:values).map(&:flatten)] rescue {} end ❯ array = [{ key: 1, value: 'one' }, { key: 2, value: 'two' }] ❯…
Rails console from one of my Rails Project It´s better to wait for a productive programmer to become available than it is to wait for the first available programmer to become productive. — Steve McConnell What is ~/.irbrc file? 🔖 After work with multiple Rails apps, you might have some methods and preferred ways of working with them. i.e. you’re using few generalized methods or…
Image from unsplash.com In last few years, social media has made the world a more connected place. Our daily life is incomplete or we can say we human beings survive on food, water, air, and social media. We share every personal information on social platforms every day and living in an illusion that we are secure and have a private life. All social media connections can access your personal…
Image from unsplash.com After a few years of continuous development, your rails application becomes larger and it’s good practice to do some cleanup. One of the most obvious cleanups is cleaning up unused routes. As your rails application grows, at the time of adding a route for new action, developers sometimes add resources :objects in config/routes.rb file rather than adding a single member or…
Credits: Google Images whenever gem is used when there’s need of run specific job at particular intervals, say - - send invoices - send daily reports - send reminder notifications etc.. Once you setup whenever, it will create a schedule.rb file under config directory. You can edit it to schedule particular task. Suppose we need to send daily sales reports at 9:00 AM every day: # Send daily sales…
Credits: Google Images Validations They are used to ensure that only valid data is saved into your database. i.e. check user email presence, check email uniqueness etc. Callbacks They are methods that get called at certain moments of an object’s life cycle. With callbacks it is possible to write code that will run whenever an object is created, saved, updated, deleted, validated, or loaded from…
Workspace is used to organize your apps into tasks. i.e. you may keep your chat applications in one workspace and coding ide into other workspace. If you work with any of the older versions of the ubuntu i.e. 14.04 or 16.04, and upgraded to 18.04 recently, you’ll notice that workspace grid doesn’t work same way as working in older versions. You can’t use it as 2 x 2 grid or so.
Hello! I have been around more than four years in IT industry. Now it’s time to contribute something to the community. Before I started writing, I searched many online tools and plugins which provide amazing platform for creating blog and chose medium as I find it more easy and convenient way of blogging for beginners. After writing number of articles on medium, I started my own blog in Hugo &…