Tag Archives: Ruby on Rails

Adding a radius search to your Ruby on Rails 5 application and PostgreSQL

Recently one of my project need to create a functionality for location based search. I choose PostgreSQL as database because I want to use some power of PostgreSQL.

So I want to create a functionality where I can send three param in a PostgreSQL and this database will return me location within this radius.  So I want to search what locations are within X meters of these coordinates.

Using PostgreSQL is lot easier.

First you need to enable some plugin for PostgreSQL.

  CREATE EXTENSION cube;
  CREATE EXTENSION earthdistance;

Now you can run query like:

SELECT \"franchises\".* FROM \"franchises\" WHERE (earth_box(ll_to_earth(40.810649, -73.598605), 2000) @> ll_to_earth(latitude, longitude))

You can also create a scope in rails model.

scope :within_radius, lambda {|latitude, longitude, metres| where("earth_box(ll_to_earth(?, ?), ?) @> ll_to_earth(latitude, longitude)", latitude, longitude, metres) }

And that’s it. You can call

  Franchise.within_radius(43.6422125, -79.3744256, 5000) 

and you’ll have a list of franchises within 5 km of NY.

Happy coding 🙂

zsh: command not found: bundle error

I have installed zsh in my ubuntu 16.04, but after install rails when trying to bundle install I found following error in my console:

zsh: command not found: bundle (after gem install bundle)

After searching on google I found following solution from stackoverflow.com:

  • echo ‘export PATH=”$HOME/.rbenv/bin:$PATH”‘ >> ~/.zshenv
  • echo ‘eval “$(rbenv init -)”‘ >> ~/.zshenv
  • echo ‘source $HOME/.zshenv’ >> ~/.zshrc
  • exec $SHELL

Running all those commands one by one will solve this problem.

Error installing rmagick on Ubuntu

While running bundle install I am getting this error:

$ gem install rmagick Building native extensions. This could take a while...

ERROR: Error installing rmagick: ERROR: Failed to build gem native extension. Can't install RMagick 2.13.2. Can't find Magick-config

I have solve this problem by installing rmagick and libmagick++-dev package

Install imagemagick:

sudo apt-get install imagemagick

Install rmagick:

$ sudo apt-get install libmagick++-dev

Create custom error pages dynamically in ruby on rails 4

The default status code templates are served by a Rack exception application. You can override this to be any Rack compatible app. To override this you need to add following line in your application.rb file.

# config/application.rb
config.exceptions_app = self.routes

Now we need to create ErrorsController:

class ErrorsController < ApplicationController
  def show
    @exception = env['action_dispatch.exception']
    write_to_log_file
    render action: request.path[1..-1]
  end

  def write_to_log_file
    if @exception.present?
      logger.error("Error occured: #{@exception.message}, Status: #{status_code}\n Time: #{Time.now}")
    end
  end

  protected

  def status_code
    params[:code] || 500
  end
end

In show method we have added a function to write the exception to log file.

Now create templates for each status code in errors directory. I have created three template for 404.html.erb, 422.html.erb and 500.html.erb

# app/views/errors/404.html.haml
%h1 404 - Not Found

Now create route for this errors:

# config/routes.rb
 %w( 404 422 500 ).each do |code|
    get code, :to => 'errors#show', :code => code
 end
 

And that’s it for dynamic error page.

Happy coding 🙂

Create RSS from your ruby on rails application

For one my recent project need RSS feed. So I have created myself.

This will show you how to create a RSS feed that the Feed Validator considers valid.

First create a FeedsController to host the RSS feed.

class FeedsController < ApplicationController

  layout false

  def rss
    @posts = Post.published_posts.limit(50)
  end

end

Then create a view in views/feeds/rss.rss.builder for RSS.

xml.instruct!
xml.rss :version => '2.0', 'xmlns:atom' => 'http://www.w3.org/2005/Atom' do

  xml.channel do
    xml.title 'Feed title'
    xml.description 'Feed description'
    xml.link root_url
    xml.language 'en'
    xml.tag! 'atom:link', :rel => 'self', :type => 'application/rss+xml', :href => posts_url

    for post in @posts
      xml.item do
        xml.title post.title
        xml.category post.category.name
        xml.pubDate(post.created_at.rfc2822)
        xml.link post_url(post)
        xml.guid post_url(post)
        xml.description(h(post.body))
        xml.image_url post.image_url
      end
    end

  end

end

Create a route to the feed in config/routes.rb:

get 'feed.rss', to: 'feeds#rss', :format => 'rss'

You can get browsers to auto-detect your Rails blog rss feed with a single line of Ruby on Rails code:

<%= auto_discovery_link_tag(:rss, "http://example.com") %>

That’s it.

Happy Coding 🙂

The program ‘bundle’ is currently not installed

This is a common problem when you first time install a new version of ruby. To fix this problem please follow below steps:

Step one:
Set up the PATH variable for the installed ruby executable
(Suppose the installed ruby is ruby-2.1.5):

Step two:

PATH=$PATH:$HOME/.rvm/gems/ruby-2.1.5/bin

Step three:

gem install bundler

(if bundler is not installed)

Final Step:

rvm use ruby-2.1.5 --default

(–default is optional).

This will fix your problem.

Hope it helps 🙂