Enumerator: When to Use and Why are they so special?


Bookmark and Share

In this post, we’ll take a look at the basics of Enumerator, When to use it and Why they are so special. So let’s begin!

As the name implies Enumerator is used for iterating over a collection of items. It allows both internal and external iteration.

So how do we Create an Enumerator?

There are 3 different ways to create it. They are from,

  • A Block,
  • An Enumerable,
  • A Blockless Enumerable Method Call.

Let’s have a look on each of the method now.

From a Block

We can create an enum by passing a block to its constructor. A yielder object will be passed to this block. The yielder’s #<< method can be used to define the elements. Enumerator#next can then be used to provide iteration.

Eg:

From an Enumerable

The most common way to create an Enumerator is from an Enumerable object, specifically, an object that defines a #each method. Object#to_enum is implemented to return a new Enumerator which will enumerate by sending #each to its receiver.

Eg:

From a Blockless Enumerable Method Call

There are several Enumerable methods that take a block and returns an Enumerator when called without a block. For instance, calling Array#select without a block will return an Enumerator with an #each method that will filter like #select.These blockless calls …

Read More

Spice up your boring IRB (Irbtools)


Bookmark and Share

IRB stands for interactive ruby, it is a tool for interactively executing ruby expressions read from a standard input. To invoke it, type irb at the shell or command prompt, and begin entering Ruby statements and expressions. But it has some limitations. A solution to this is called ‘irbtools‘, which make using irb easier and more fun. It improves Ruby’s irb console like colored output and lots of helpful methods.

Setup

Install the gem by using:

or

Add it to your project’s Gemfile:

Usage

IRB executes code in ~/.irbrc on start-up.To use irbtools, put the following code in ~/.irbrc file:

We can start IRB directly from the code by calling,

When installing irbtools, some gems will not be installed. For example, the bond gem for better auto-completion. These are packaged as irbtools-more (requires ruby version >= 2.4). To use irbtools-more, change the .irbrc to:

and edit Gemfile as

For example, the output looks like:

Irbtools

Features

  • Colorized and output as comment by wirb and fancy_irb
  • Nice IRB prompt and IRB’s auto indention
  • Includes stdlib’s FileUtils: ls, cd, pwd, ln_s, rm, mkdir, touch, cat
  • Many debugging helpers:
    • ap – awesome_print
    • q –like p, but on …
  • Read More

    PStore, a little known feature in the standard library


    Bookmark and Share

    PStore(persistent store) implements a file based persistence mechanism based on a Hash. It writes Ruby objects to an external file so it can access easily if needed. If an I/O error occurs while PStore is writing to its file, then the file will become corrupted.You can prevent this by setting pstore.ultra_safe = true. Also, it supports thread-safe and uses Marshal internally.

    To use this library, you must require it and instantiate a new object.

    Which would create a file that stores the content to be written.

    To store or retrieve data from the data store, you must open a transaction. Here transaction is a protective wrapper around SQL statements to ensure changes to the database only occur when all actions succeed together. We can access the content of database only through this transaction.

    At the end of the transaction, all changes are committed.

    Public Instance methods

    Instance methods are methods that are called on an instance of a class. We can use the below methods while using PStore instances.

    • p[name]=obj

    Stores obj in the database under the key name. When the transaction is completed, all objects accessed reflexively by obj  are saved in a file.

    • p.root?(name)

    Returns true if the key …

    Read More

    Disabling transaction block during migration


    Bookmark and Share

    Migrations are used to modify your database. By default, all migrations run inside a transaction. You can disable the transaction during migration. Let’s have a look on how to disable transaction block!

    Migrations can manage the evolution of a schema used by several physical databases. It’s a solution to the common problem of adding a field to make a new feature work in your local database, but being unsure of how to push that change to other developers and to the production server. With migrations, you can describe the transformations in self-contained classes that can be checked into version control systems and executed against another database that might be one, two, or five versions behind.

    In Rails, transactions are protective blocks around SQL statements that ensure changes to the database only occur when all actions succeed together. Transactions enforce the integrity of the database and guard the data against program errors or database break-downs. So basically you should use transaction block whenever you have a number of statements that must be executed together or not at all.

    Eg:

    disable_ddl_transaction!()

    DDL can’t run inside a transaction block. You can disable DDL transactions in Rails, using disable_ddl_transaction. It is used in …

    Read More

    How to write your own Rack middleware


    Bookmark and Share

    How to write your own Rack middleware

    Rack is a Ruby package which provides an interface for a web server to communicate with the application. It is very easy to add middleware components between the web server and the app to customize the way your request/response behaves. The middleware component sits between the client and the server, processing inbound requests and outbound responses. Rack Middleware is an implementation of the pipeline design pattern for web servers using Rack.

    For example with Rack, we can have separate stages of the pipeline:

    • Authentication: Checks whether the login details are correct or not when the request arrives.
    • Authorization:  It performs role-based security. i.e. checks whether the user is authorized to perform the particular task.
    • Caching: Return a cached result if the request is already processed.
    • Decoration: Enhance the request to make downstream processing better.
    • Performance & Usage Monitoring: Status get from the request and response.
    • Execution: actually handle the request and provide a response.

    Next, we will see how to build our own rack middleware.

    Building your own …

    Read More

    Using gmail to send email in Ruby on Rails


    Bookmark and Share

    Emails can be sent from you Rails application through many services like mandril, sendgrid, amazon SES. In this article, we would be explaining how we can send email using a Gmail credentials. Even though we can’t use it in production scenario due to the 500 email per day limitation, it would help us in prototyping an application quickly and also for cases where you want to send actual email in your development environment. Action Mailer is the ruby library in rails that will help us to do this.

    Action Mailer allows you to send emails from your application using mailer classes and views. Mailers work very similarly to controllers. They inherit from ActionMailer::Base and live in app/mailers, and they have associated views that appear in app/views.To setup action mailer, must do the following:

    1. Configuring the mailer in your environment file
    2. Generating the mailer
    3. Defining mailer action
    4. Generating the mailer view
    5. Delivering the email

    Action Mailer Configuration

    To configure action mailer add the following to your appropriate config/environments/$RAILS_ENV.rb file:

    Eg:

    Generating the mailer

    As you generate a controller for your application, you can …

    Read More

    Different ways to run Shell Commands in Ruby


    Bookmark and Share

    During development of an application, there will come cases when we need to access system command from our program itself. In some cases we just need to know if the status was complete, in some cases, we also need to know the output the application returns.But before we start, let’s find out what Shell Commands are. Simply put, the shell is a program that takes your commands from the keyboard and gives them to the operating system to perform. There are several additional shell programs available on a typical Linux system. Described below are 6 different way to execute a shell script from ruby and their properties.

  • Exec
  • System
  • Backticks ()
  • IO#popen
  • open3#popen3
  • open4#popen4
  • Exec

    Kernel#exec (or simply exec) replaces the current process by running the given command, which can take one of the following forms:

    exec(commandline)
    command line string which is passed to the standard shell

    exec(cmdname, arg1, …)
    command name and one or more arguments (no shell)

    exec([cmdname, argv0], arg1, …)
    command name, argv and zero or more arguments (no shell)

    In the first form, the string is taken as a command line that is subject to shell expansion before being executed.

    In the second form (exec(“command1”, “arg1”, …)), the first is taken …

    Read More