Learn about the concept of Active Job in Rails

seen from United States
seen from Australia
seen from New Zealand
seen from South Korea
seen from Australia

seen from Malaysia
seen from Kyrgyzstan
seen from Yemen
seen from Kyrgyzstan
seen from United States

seen from Switzerland
seen from Chile
seen from British Virgin Islands

seen from United States
seen from United States
seen from China
seen from Taiwan

seen from Switzerland

seen from United States

seen from Egypt
Learn about the concept of Active Job in Rails
Many times, we need to track the page views of any page such as profile page, shopping sites page in a Ruby on Rails applications, for which we can make use of Impressionist gem to track those page details easily.
It is a lightweight plugin that logs impressions per action or manually per model. We can log impressions multiple times per request. And we can also attach it to a model.
Below are the simple steps needed to follow to implement it:
Step 1: Create a sample app using scaffold.
Step 2: Add “gem ‘impressionist’” gem to the Gemfile and install it by running bundle install command.
gem ‘impressionist’, git: ‘https://github.com/jordanhudgens/impressionist’
Step 3: Now generate the impressions table migration by running the below commands:
rails g impressionist
rake db:migrate
Step 4: Now we need to update our controller that we want to add the impression or page views counting system. So first we have add the following method in our controller with mentioning the list of actions that we want to count:
And then update the controller action with the impressionist method:
Step 5: We need to add the new counter cache column to the model that we are working with. Run the following command:
rails g migration add_impressions_count_to_blogs impressions_count:integer
rails db:migrate
Now we can update the model for tracking the hits:
Step 6: Now we can display how many views this Blog has.
Source: Track Page Impressions in Ruby on Rails
GraphQL with Ruby
Now a day’s most of the web or mobile applications fetch data from server which is stored in a database. REST API provides an interface to stored data that require by the applications. GraphQL is a query language for REST API's not for server databases.
It is database agnostic and effectively can be used in any context where an API is used. GraphQL provide platform for declarative data fetching where client need to specify what data needs from API in response.
Instead of multiple endpoints that return fixed data structures, a GraphQL server only exposes a single endpoint and responds with precisely the data a client asked for. GraphQL minimizes the amount of data that needs to be transferred over the network and improves applications operating under these conditions.
Introduction to GraphQL API on Ruby on Rails
Start with adding gem in Gemfile
gem ‘graphql’
Run command
bundle install
Run command
rails generate graphql:install
Above command will add graphiql-rails in installation. Let Post API where clients can get post and create post. The post has an ID, title and description, goes into app/graphql/types/post.rb
Post = GraphQL::ObjectType.define do name 'Post' description 'Post creation' field :id, !types.Int ... end
The GraphQL ID type is a string, so we use Int. GraphQL defines a schema with queries (eg. get post) and mutations (eg. create a post), which typically goes into app/graphql/schema.rb.
Schema = GraphQL::Schema.define do query Query mutation Mutation end
The query root returns an post by ID, implemented in app/graphql/queries.rb.
Query = GraphQL::ObjectType.define do name 'Query' field :post, Post do argument :id, !types.Int description 'Get an post by ID.' resolve ->(_obj, args, _ctx) { OpenStruct.new( ... ) } end end
A mutation creates posts in app/graphql/mutations/create_post_mutation.rb. Use Relay, a data fetching framework that makes it easy.
CreatePostMutation = GraphQL::Relay::Mutation.define do name 'createPost' input_field :title, !types.string input_field :description, !types.string return_type Post resolve ->(_object, inputs, _ctx) { OpenStruct.new( id: 2, ... ) } end
GraphQL Controller
GraphQL accepts a single JSON payload via POST in a typical Rails controller in app/controllers/graphql_controller.rb.
class GraphqlController < ApplicationController def execute result = Schema.execute( query, variables: variables, context: context, operation_name: operation_name ) render json: result end private def query ... end def operation_name ... end def context ... end def variables ... end end
Set routes in config/routes.rb
Rails.application.routes.draw do post '/graphql', to: 'graphql#execute' end
Start the rails application
using rails s
and type http://localhost:3000/graphql in browser for local environment for rails.
Source: http://www.cryptextechnologies.com/blogs/graphql-with-ruby
How to manage postgre through command line in Ubuntu?
Step 1: First install postgres in Ubuntu system using following commands.
$ sudo apt-get update $ sudo apt-get install postgresql postgresql-contrib libpq-dev
To check psql (postgres) version.
$ psql –version
Step 2: Now to create root user and password for psql.
$ sudo -u postgres createuser -s root $ sudo -i -u postgres
Now, you are in postgres environment.
postgres@admin:~$
Now, use the following command to enter and manage psql.
postgres@admin:~$ psql
Now, set the password for psql username “root”.
postgres=# \password root enter password confirm
Now, you can exit from psql using following command
postgres=# \q
Step 3: Create new user and database in psql
$ sudo su postgres $ psql -c "create user mack with password 'mack'" $ psql -c "create database mackdb owner mack" $ sudo -i -u postgres postgres@admin:~$ psql
Step 4: Give all privileges over database to a particular user.
postgres=# grant all privileges on database mackdb to mack
You might be face this type of error while rakedb:create
PG::InsufficientPrivilege: ERROR: permission denied for relation schema_migrations rakedb:create
postgres=# ALTER USER mack WITH SUPERUSER;
To list all the users of psql.
postgres=# \du
To list all the databases of psql.
postgres=# \l
Step 5: Take backup or dump file to the database.
$ sudo su postgres
To take the backup of psql database
postgres@admin:~$ pg_dump dbname > outfile
To dump into psql database. Go to particular directory where the dump file is present enter following command
postgres@admin:~$ pg_restore dbname < infile exit.
This is all about postgres. Hope this is helpfull.
Thank You.
Source: http://www.cryptextechnologies.com/blogs/manage-postgres-through-command-line-in-ubuntu
Sending Emails in Rails Applications
Action Mailer is the Rails component that enables applications to send and receive emails. In Rails, emails are used by creating mailers that inherit from “ActionMailer::Base” in app/mailers. Those mailers have associated views that appear alongside controller views in app/views.
Now we will build a rails application which will send an email to the user when a new user is created. Let’s create a new rails application.
$ rails new sample_app $ cd sample_app $ rails generate scaffold user first_name:string last_name:string phone_number:string email:string $ rake db:migrate
Action Mailer- Configuration:
Following are the steps you have to follow to complete your configuration before proceeding with the actual work.
We will just add following lines of code in config/environments/development.rb
config.action_mailer.delivery_method = :smtp
#It tells ActionMailer that you want to use the SMTP server.
Generate a Mailer :
We now have a basic application, let’s make use of ActionMailer. The mailer generator is similar to any other generator in rails.
$ rails g mailer example_mailer
#This will create a example_mailer.rb in the app\mailer directory.
Now we open up app/mailers/example_mailer.rb and add a mailer action that sends users a signup email.
app/mailers/example_mailer.rb
Now let’s write the mail we want to send to our users, and this can be done in app/views/example_mailer. Create a file sample_email.html.erb which is an email formatted in HTML.
app/views/example_mailer/sample_email.html.erb
We also need to create the text part for this email as not all clients prefer HTML emails. Create sample_email.text.erb in the app/views/example_mailer directory.
app/views/example_mailer/sample_email.text.erb
Now in the controller for the user model app/controllers/users_controller.rb, add a call to ExampleMailer.send_signup_email when a user is saved.
app/controllers/users_controller.rb
That’s it! When a new user object is saved, an email will be sent to the user via SendGrid
Source: Send Mail in Ruby Application
Bulk Mailing Using Sidekiq
Introduction:
Sometimes the rails application requires sending the bulk mails using action mailers on the single attempt. The user can be able to send them seamlessly. But, this task is not possible in synchronous way. This will affect whole application performance and will take a lot of time to load the respective pages.
To overcome this problem rails community have enormous kinds of solutions. Among them sidekiq is the best choice to overcome this kind of problems.
The sidekiq is a full-featured background processing framework for Ruby. It aims to be simple to integrate with any modern Rails application and much higher performance than other existing solutions.
The Redisis an open source (BSD licensed), in-memory data structure store, used as a database, cache and message broker. It supports data structures such as strings, hashes, lists, sets, sorted sets with range queries, bitmaps, hyperlog logs and geospatial indexes with radius queries.
The Action Mailer is a service provided by rails to send the mails on respective emails ids. To send an email we must have to invoke deliver method of actionmailer.
To send mails asynchronously we have to use the sidekiq.
Integration Setup:
Add sidekiq into your rails application by including it into your Gemfile and run the bundle command.
#Gemfile
gem ‘sidekiq’
To run sidekiq, run the following command:
$ bundle exec sidekiq -d -L log/sidekiq.log -C config/sidekiq.yml(default development mode)
$ bundle exec sidekiq -d -L log/sidekiq.log -C config/sidekiq.yml -e production (production mode)
Sending Delayed Emails:
Sidekiq provides asynchronous emails sending provision with Action Mailer. That will be performed by adding below three methods to the ActionMailer module.
.dealy
The .delay method will call the action mailer method and add this mail into to DelayedMailer queue for processing.
For ex., NewsMailer.delay.newsmailer(@email)
.delay_for(interval)
Here, user can be proviode inerval time before sending emails asynchronously.
For ex., NewsMailer.delay_for(1.day).newsmailer(@email)
.delay_until(timestamp)
Here, user can set the timestamp for sidekiq. Sidekiq will wait until the provided time to send the email.
For ex., NewsMailer.delay_until(3.day.from_now).newsmailer(@email)
Sending Bulk delayed Emails:
The below example illustrated the way to send bulk emails.
ApplicationMailer.delay.new_article_mail(@article)
Here., ApplicationMailer is a class have new_article_mail(article) method. We used .delay method to set the delay for sending mail asynchronously.
# Send an email to all the users if new project has been posted in website.
def new_article_mail(article) @article = article all_users("New article added in GXP") end private def all_users(subject) User.all.map{ |user| @user = user send_mail(user.email, subject).deliver } end def send_mail(email, subject) mail to: email, subject: subject end
Here, new_article_mail method has one more method all_users in which we are calling send_mail method for sending an email to the individual user.
Source: Bulk Mailing Using Sidekiq
Creating a simple Ruby on Rails application using Devise
Creating a simple Ruby on Rails application using Devise
Devise is a flexible authentication solution for Rails. It is a complete MVC solution based on Rails engines. It allows you to have multiple models signed in at the same time. It hashes and stores a password in the database to validate the authenticity of a user while signing in. The authentication can be done both through POST requests or HTTP Basic Authentication. STEP 1. gem ‘devise’ install.…
View On WordPress
How to combine data from two different tables into new rows to be displayed as one table in Rails application?
How to combine data from two different tables into new rows to be displayed as one table in Rails application?
Let’s start with an example that you have two different tables called InternalEmail and ExternalEmail. internal_emails Id (integer) sender_id (integer) content (text) Subject (character varying) recipient_email (character varying) Status (character varying) created_at (timestamp without time zone) updated_at (timestamp without time zone) 1 52 internal_content_1 internal_subject_1 44 accepted…
View On WordPress