Running Particles.js in Rails

Prerequisites

  • Must be on a project that uses Ruby on Rails.

What is Particles.js?

Step(s)

First off navigate to http://vincentgarreau.com/particles.js/ to download the particles.js zip file.

The simply extract the zip file.

Next, create a new div in your application.html.erb layout file ex:

 

Now navigate to your application.js file and add

//= require turbolinks
//= require particles.min
//= require_tree .

Then copy the fileparticles.min.js from the folderparticles.js-master extracted from the zip file to the directoryassets/javascripts.

Next up let us add a little bit of styling to the div we created earlier. So add

#particles-js {
  width: 100%;
  height: 500px;
  background: #333;
}

to the file application.scss under the directory assets/stylesheets.

Finally, add the following javascript configuration code to one of the coffee scripts you own which are always loaded.

$ ->
  particlesJS('particles-js',
    {
      "particles": {
        "number": {
          "value": 80,
          "density": {
            "enable": true,
            "value_area": 800
          }
        },
        "color": {
          "value": "#ffffff"
        },
        "shape": {
          "type": "circle",
          "stroke": {
            "width": 0,
            "color": "#000000"
          },
          "polygon": {
            "nb_sides": 5
          },
          "image": {
            "src": "img/github.svg",
            "width": 100,
            "height": 100
          }
        },
        "opacity": {
          "value": 0.5,
          "random": false,
          "anim": {
            "enable": false,
            "speed": 1,
            "opacity_min": 0.1,
            "sync": false
          }
        },
        "size": {
          "value": 5,
          "random": true,
          "anim": {
            "enable": false,
            "speed": 40,
            "size_min": 0.1,
            "sync": false
          }
        },
        "line_linked": {
          "enable": true,
          "distance": 150,
          "color": "#ffffff",
          "opacity": 0.4,
          "width": 1
        },
        "move": {
          "enable": true,
          "speed": 6,
          "direction": "none",
          "random": false,
          "straight": false,
          "out_mode": "out",
          "attract": {
            "enable": false,
            "rotateX": 600,
            "rotateY": 1200
          }
        }
      },
      "interactivity": {
        "detect_on": "canvas",
        "events": {
          "onhover": {
            "enable": true,
            "mode": "repulse"
          },
          "onclick": {
            "enable": true,
            "mode": "push"
          },
          "resize": true
        },
        "modes": {
          "grab": {
            "distance": 400,
            "line_linked": {
              "opacity": 1
            }
          },
          "bubble": {
            "distance": 400,
            "size": 40,
            "duration": 2,
            "opacity": 8,
            "speed": 3
          },
          "repulse": {
            "distance": 200
          },
          "push": {
            "particles_nb": 4
          },
          "remove": {
            "particles_nb": 2
          }
        }
      },
      "retina_detect": true,
      "config_demo": {
        "hide_card": false,
        "background_color": "#b61924",
        "background_image": "",
        "background_position": "50% 50%",
        "background_repeat": "no-repeat",
        "background_size": "cover"
      }
    }
  );

And that’s it, you now have a div which implements Particles.js

 

Advertisements

Elasticsearch Ruby on Rails intergration

Prerequisites

  • Ruby on Rails installed
  • Basic project created
  • Basic knowledge on Ruby on Rails
  • Mac or Linux OS
  • Homebrew is installed (If not, follow the instructions located HERE)

What is Elasticsearch?

Elasticsearch is a easy to use, free search engine that has recently been picking up steam in the market. It is developed by “Elastic” who has developed a number of tools including Logstash and Kibana (Which i will be going over when i find the need to integrate them into my current project). To view more about Elasticsearch visit their website located HERE.

Steps

First of all we need to download Elasticsearch

brew install elasticsearch

now start it up

elasticsearch --config=/usr/local/opt/elasticsearch/config/elasticsearch.yml

to verify that elasticsearch is up and running curl localhost

curl -X GET http://localhost:9200

to retrieve the given output

{
  "status" : 200,
  "name" : "Nameless One",
  "version" : {
    "number" : "1.2.2",
    "build_hash" : "9902f08efc3ad14ce27882b991c4c56b920c9872",
    "build_timestamp" : "2014-07-09T12:02:32Z",
    "build_snapshot" : false,
    "lucene_version" : "4.8"
  },
  "tagline" : "You Know, for Search"
}

Good job, you now have elasticsearch installed and running. Next we will be integrating it into our Ruby on Rails project. To do this we will be using the “elasaticsearch-rails” gem who’s github documentation is available HERE.

First of all lets add the gems to our Gemfile

gem 'elasticsearch-model', git: 'git://github.com/elasticsearch/elasticsearch-rails.git'
gem 'elasticsearch-rails', git: 'git://github.com/elasticsearch/elasticsearch-rails.git'

and run bundle install

bundle install

Next we need to let ruby know which models we wish to be searchable by elasticsearch. To do this we need to change our model a little bit. I want my “Movie” model to be searchable so that is the one I’m going to be changing.

require 'elasticsearch/model'

class Movie < ActiveRecord::Base
  include Elasticsearch::Model
end

 

Notice I added the require and inclusion of the elasticsearch/model

Now we need to create the appropriate index in elasticsearch and import our models associated data. To do this it is easiest to open the rails console

rails c

and initialize the index importing the current data

Movie.index force: true

That is all it takes to setup and map elasticsearch to a model. To verify it you can now search in that given application via

Movie.search("Titanic")

and retrieve relevant results. For more in-depth documentation please visit this gems details page located HERE.

Ruby recommendation engine done easy

Prerequisites

  • Ruby on Rails installed
  • Basic project created
  • Basic knowledge on Ruby on Rails
  • Mac or Linux OS

Steps

For this how to blog we will be adding a recommendation engine to an existing Ruby on Rails project. The recommendation gem which we will be leveraging is “recommendable” which can be viewed on github HERE and additional documentation can be viewed HERE. Before we begin it is mentioned that there is a limitation to using this gem. The limitation is that using this gem only one model will be able to have a recommendation engine associated to it. If that is not a issue then let us proceed.

To get things started let us add the following line to our Gemfile

gem 'recommendable'

and execute

bundle install

to install the gem and all of its dependencies.

Next up we need to create a new file in the config/initializers directory. The content of this file should look like:

require 'redis'

Recommendable.configure do |config|
  # Recommendable's connection to Redis
  config.redis = Redis.new(:host => 'localhost', :port => 6379, :db => 0)

  # A prefix for all keys Recommendable uses
  config.redis_namespace = :recommendable

  # Whether or not to automatically enqueue users to have their recommendations
  # refreshed after they like/dislike an item
  config.auto_enqueue = true

  # The number of nearest neighbors (k-NN) to check when updating
  # recommendations for a user. Set to `nil` if you want to check all
  # other users as opposed to a subset of the nearest ones.
  config.nearest_neighbors = nil
end

after that you need to modify the Model you wish to add the recommendation system to. Im going to modify the User model because that is where I’m adding it.

class User < ActiveRecord::Base
  recommends :movies, :books
end

As you can see, all you need to do here is add a line linking recommends to different existing database tables.

Now all you need to do is install redis which is a queuing system the recommends gem uses. This can be done easily on mac with the following line:

brew install redis

Or on linux via:

sudo apt-get install redis-server
redis-server

Once it is installed configure it to startup at login

ln -sfv /usr/local/opt/redis/*.plist ~/Library/LaunchAgents
launchctl load ~/Library/LaunchAgents/homebrew.mxcl.redis.plist

 and restart your server and you are good to go. For information on how to use the gem please visit http://davidcel.is/recommendable/.

Ajax requests for partial renders for Ruby on Rails

Prerequisites

  • Ruby on Rails installed
  • Basic project created
  • Basic knowledge on Ruby on Rails

Steps

Consider the basic scenario…

You have one div in the view you wish to be refreshed with different content when a button is clicked however you do not with the entire page to be redrawn.

So in my index method one could have:

# /controller/movie_controller.rb
def index
  @movie = Movie.first
end

And for simplicity sake, the view for this controller could be:

# /views/movie/index.html
<%= render partial: "movie_media_box", locals: {movie: @movie} %>

This renders the html located in the “/views/movie/_movie_media_box.html.erb here and passes it the “movie” variable. A basic partial to be changed would look like:

# /views/movie/_movie_media_box.html.erb
<div id=movie-<%=movie.id%>>
 <label><%=movie.title%></label>
</div>

Now, the button you wish to trigger the changing of this div should look something like:

# Anywhere you want it
<%= link_to "change", {:controller => "movies", :action => "change_movie", :id => movie.id}, :remote => true%>

What this is doing is creating a link which will call the “change_movie” method in the “movies” controller passing it “id” as a parameter. The “remote =>true” is letting rails know to handle this as a ajax request.

The “change_movie” method should look similar to:

# /controller/movie_controller.rb
def change_movie
  @previous_id = params["id"]
  @new_movie = Movie.last
  respond_to do |format|
    format.js
  end
end

Notice how this is not returning a html file, instead it is returning a JS file which is named “/views/movie/change_movie.js.erb”. In this file is where will be changing the content of that div.

# /views/movie/change_movie.js.erb
$("#movie-<%=@previous_id%>").html("<%= escape_javascript(render partial: 'movie_media_box', locals: { movie: @new_movie } ) %>")

This is using jQuery to find the div with the id “movie-X” and replace the html inside of it with the partial “movie_media_box” passing it “@new_movie” instead of the previous movie being used.

And thats it, you now have a basic ajax request working for partial renders for Ruby On Rails!

I referred to: https://coderwall.com/p/kqb3xq/rails-4-how-to-partials-ajax-dead-easy to get my first understanding on how to do this.