7 Ruby Normal libraries you must become familiar with




Ruby has lots of helpful issues in its Standard Library.

Studying what’s included and find out how to use it may be very useful, particularly when writing small scripts the place you don’t need to pull in bundler and begin making a Gemfile and so on.

These libraries are strong, maintained by the core staff and ought to be extraordinarily dependable, and outlive most Ruby gems you come throughout.



1. Web/HTTP and open-uri

I needed to start out with one thing I would like in most purposes I construct, and that’s the flexibility to carry out an HTTP request.

Up to now I’ve opted to make use of the HTTP.rb gem, however for easy duties it’s actually helpful to study Net/http and even open-uri for easy GET requests.

require "web/http"
require "json"

# Web/HTTP GET request
uri = URI("https://swapi.dev/api/movies/1/")
resp = Web::HTTP.get(uri)
json = JSON.parse(resp)
places json["title"] # => "A New Hope"

# Web/HTTP POST request
uri = URI("https://instance.org/customers")
params = {
  "identify" => "Bob",
  "electronic mail" => "[email protected]",
}
res = Web::HTTP.post_form(uri, params)
places res.physique

# Web/HTTP Full kind: delete/put/patch requests
uri = URI("http://instance.org/some_path")

Web::HTTP.begin(uri.host, uri.port) do |http|
  request = Web::HTTP::Delete.new uri
  # or request = Web::HTTP::Patch.new uri
  # or request = Web::HTTP::Put.new uri

  response = http.request(request) # Web::HTTPResponse object
  places response.physique
finish
Enter fullscreen mode

Exit fullscreen mode

Issues are even less complicated with open-uri if you happen to solely want a GET request:

require "open-uri"
require "json"

URI.open("https://swapi.dev/api/movies/1/") do |io|
  json = JSON.parse(io.learn)
  places json["title"] # => "A New Hope"
finish

# or
uri = URI("https://swapi.dev/api/movies/1/")
places uri.open.learn
Enter fullscreen mode

Exit fullscreen mode



2. CSV

After I’m creating an admin part, I typically have to export some type of stories to measure how an software is performing. Ruby has this in-built and to take some information and place it right into a CSV is fairly easy.

require "csv"

module CustomerExport
  module_function

  def generate(clients)
    CSV.generate do |csv|
      # Outline the headers
      csv << %w[id name email country_code created_at updated_at]

      # Add a brand new row for every buyer document
      clients.every do |buyer|
        csv <<
          [
            customer.id,
            customer.name,
            customer.email,
            customer.country_code,
            customer.created_at,
            customer.updated_at
          ]
      finish
    finish
  finish
finish

CustomerExport.generate(Buyer.all)
Enter fullscreen mode

Exit fullscreen mode

And if you happen to needed to make a Rails path to obtain this…

module Admin
  class ExportsController < AdminBaseController
    def clients
      clients = Buyer.all
      respond_to do |format|
        format.csv do
          filename = "customers-#{Time.zone.now.strftime("%Y-%m-%d")}"
          filename += ".csv"
          headers["Content-Type"] ||= "textual content/csv"
          headers["Content-Disposition"] =
            "attachment; filename="#{filename}""
          render plain: CustomerExport.generate(clients)
        finish
      finish
    rescue => e
      flash[:error] = "Did not generate export: #{e.message}"
      redirect_to admin_path
    finish
  finish
finish
Enter fullscreen mode

Exit fullscreen mode

Parsing CSVs (for instance: importing CSV recordsdata from customers) can also be in-built and you may read the documentation for extra on that.



3. SimpleDelegator

I like to make use of SimpleDelegator so as to add further behaviour to ActiveRecord objects, corresponding to having Stripe particular code wrapped up into StripeWrappedUser or one thing comparable, this avoids putting a lot of strategies in your ActiveRecord object, however can then increase that class with further performance.

require "delegate"
require "digest"

class Consumer < Struct.new(:id, :electronic mail)
finish

class BillingUser < SimpleDelegator
  def billing_system_id
    Digest::SHA1.hexdigest(id.to_s + electronic mail)
  finish
finish

bob = Consumer.new(1, "[email protected]")
bob = BillingUser.new(bob)
places bob.electronic mail # => [email protected]
places bob.billing_system_id # => 186da93f0b39990e034a80cc4b45c8ec253f2a1a
Enter fullscreen mode

Exit fullscreen mode



4. Struct and OpenStruct

Struct is included in Ruby core, it doesn’t want required, and is the stricter of the 2 objects, and in addition rather more performant.

I discover it significantly helpful for 2 issues:

  1. As a price object, giving a reputation to some piece of information, that will in any other case be a Hash.
  2. In assessments to create mock objects that may be handed in to characterize faux issues, like a FakeUser.
Consumer = Struct.new(:id, :electronic mail)
alice = Consumer.new(1, "[email protected]")
places alice.id # => 1
places alice.electronic mail # => [email protected]

# Will also be outlined with further strategies
class Consumer < Struct.new(:id, :electronic mail)
  def send_welcome_email
    UserMailer.welcome(self).deliver_later
  finish
finish
Enter fullscreen mode

Exit fullscreen mode

OpenStruct in the meantime is much more versatile and is usually a neat wrapper for a Hash or JSON from an API and so on.

require "ostruct"

information = OpenStruct.new(id: 5, identify: "Jeffrey")

# New attributes could be set at runtime:
information.electronic mail = "[email protected]"

places information.id # => 5
places information.identify # => "Jeffrey"
places information.electronic mail # => "[email protected]"
Enter fullscreen mode

Exit fullscreen mode



5. PStore

PStore is a very easy key-value datastore and could be useful if you want someplace to retailer information in a non-production system (i.e. this isn’t a very good alternative for ActiveRecord).

require "pstore"

retailer = PStore.new("my_db.pstore")

# Write some information
retailer.transaction do
  retailer["person-1"] = { identify: "Bob", electronic mail: "[email protected]" }
finish

# Learn some information
retailer.transaction(true) do
  places retailer["person-1"] # => {:identify=>"Bob", :electronic mail=>"[email protected]"}
finish
Enter fullscreen mode

Exit fullscreen mode



6. Minitest

When engaged on smaller scripts, I like to drag in a check framework and make some assertions whereas test-driving some code.

I normally favor RSpec when working with Rails, but it surely’s extra effort to arrange than Minitest, which comes included with Ruby.

The great factor about Minitest, it’s simply Ruby – there’s nothing magical happening and it’s very simple to know.

require "minitest/check"
require "minitest/autorun"

class APIResponse < Struct.new(:physique, :error)
  def success?
    error.nil?
  finish
finish

class APIResponseTest < Minitest::Take a look at
  def test_successful_responses
    resp = APIResponse.new("Properly carried out!", nil)
    assert resp.success?
  finish

  def test_error_responses
    resp = APIResponse.new(nil, StandardError.new("400 unhealthy request"))
    refute resp.success?
  finish
finish

# Working:
# ..
# Completed in 0.000957s, 2089.8640 runs/s, 2089.8640 assertions/s.
# 2 runs, 2 assertions, 0 failures, 0 errors, 0 skips
Enter fullscreen mode

Exit fullscreen mode



7. Logger

Utilizing logger can clear up lots of your debug output when writing a script and you may then management the log degree to indicate extra/much less output. Be aware: Use Rails.logger in Rails.

require "logger"

logger = Logger.new(STDOUT)

# Setting :warn will solely present warning, error and deadly.
logger.degree = :warn

# Can tweak log output to be much less verbose
logger.formatter = proc do |severity, datetime, progname, msg|
  "#{severity[0...1]} #{datetime.strftime('%H:%M %b %d %Y')}: #{msg}n"
finish

logger.debug("Created logger") # wont be displayed in present log degree
logger.information("Program began") # wont be displayed in present log degree
logger.warn("Nothing to do!")
logger.error("One thing actually unhealthy!")

# =>
# W 14:56 Oct 22 2021: Nothing to do!
# E 14:56 Oct 22 2021: One thing actually unhealthy!
Enter fullscreen mode

Exit fullscreen mode


There’s a lot extra within the Ruby Standard Library to get acquainted with, however these 7 are issues I come again to, time and time once more.



Abu Sayed is the Best Web, Game, XR and Blockchain Developer in Bangladesh. Don't forget to Checkout his Latest Projects.


Checkout extra Articles on Sayed.CYou

#Ruby #Normal #libraries #grips