Wednesday, 29 April 2015

css problem with activeadmin in rails

Put this line into /app/assets/stylesheets/application.css:-

*= stub active_admin

Devise user authentication in rspec

Create spec/support/controller_macros.rb

module ControllerMacros

  def login_user
    before(:each) do
      @request.env["devise.mapping"] = Devise.mappings[:user]
      user = FactoryGirl.create(:user)
      #user.confirm! # or set a confirmed_at inside the factory. Only necessary if you are using the "confirmable" module
      sign_in user
    end
  end
end

Create spec/factries.rb
 
 FactoryGirl.define do
    factory :user do |f|
        f.first_name 'sandy'
        f.email 'sandeep@ywr.com'
        f.password '12345678'
        f.password_confirmation '12345678'
  end

end

Put following in spec/spec_helper.rb

require 'rspec/rails'
Dir[Rails.root.join("spec/support/**/*.rb")].each {|f| require f}
require 'factory_girl_rails'
require 'devise'

RSpec.configure do |config|
   config.include Devise::TestHelpers, :type => :controller
  config.extend ControllerMacros, :type => :controller
end

In spec/controllers/users_controller_spec.rb

 require 'rails_helper'
require 'factory_girl_rails'
describe UsersController do
   login_user
  it "should have a current_user" do
    # note the fact that I removed the "validate_session" parameter if this was a scaffold-generated controller
    subject.current_user.should_not be_nil
  end
end


Thanks

render html in pdf in and then sent it as atachment in mail ruby on rails

Add gems:- 

gem 'wicked_pdf'
gem 'wkhtmltopdf-binary'

Run bundle install

In Controller:- 

def generate_pdf
          html = render_to_string(:action => :pdf_file, :layout => false)

      pdf = WickedPdf.new.pdf_from_string(html)
      save_path = Rails.root.join('public','users.pdf')
      File.open(save_path, 'wb') do |file| 
        file << pdf
      end

      @mail = ReminderMailer.share_email(params).deliver

      flash[:notice] = 'Email sent successfully.'
      render 'show', layout: 'simple' if !mobile_device?
  end

Tuesday, 21 April 2015

copy ssh key on server

cat ~/.ssh/id_rsa.pub | ssh <user>@<hostname> 'cat >> .ssh/authorized_keys && echo "Key copied"'

Monday, 20 April 2015

Install Redis on Amazon EC2 Linux AMI or CentOS

Install Redis 2.6 on Amazon EC2 Linux AMI or CentOS

Complete guide on installing and configuring Redis 2.6 as a service on Amazon EC2 running with Amazon Linux AMI or CentOS. The procedure should apply to Fedora and Red Hat distributions as well. In case you feel like skipping these steps, feel free to use the Github Script for an even simpler installation and configuration of Redis as a service. By the way, a hearty thanks to John over at SaltWebsites for his awesome tutorial. Also, for a tutorial on installing Redis 2.6 as a service on Ubuntu and Windows, please click here and here respectively. Another tutorial on installing and using the C- client library for Redis, Hiredis is provided here.

1. Install Linux updates, set time zones, followed by GCC and Make

sudo yum -y update
sudo ln -sf /usr/share/zoneinfo/America/Indianapolis \
/etc/localtime
sudo yum -y install gcc make

2. Download, Untar and Make Redis 2.6

wget http://redis.googlecode.com/files/redis-2.6.0-rc3.tar.gz
tar xzf redis-2.6.0-rc3.tar.gz
cd redis-2.6.0-rc3
make

3. Create Directories and Copy Redis Files

sudo mkdir /etc/redis /var/lib/redis
sudo cp src/redis-server src/redis-cli /usr/local/bin
sudo cp redis.conf /etc/redis

4. Configure Redis.Conf

sudo nano /etc/redis/redis.conf
[..]
daemonize yes
[..]
[..]
bind 127.0.0.1
[..]
[..]
dir /var/lib/redis
[..]

5. Download init Script

wget https://raw.github.com/saxenap/install-redis-amazon-linux-centos/master/redis-server

6. Move and Configure Redis-Server

Note: The redis-server to be moved below is the one downloaded in 5 above.
sudo mv redis-server /etc/init.d
sudo chmod 755 /etc/init.d/redis-server
sudo nano /etc/init.d/redis-server
redis="/usr/local/bin/redis-server"

7. Auto-Enable Redis-Server

sudo chkconfig --add redis-server
sudo chkconfig --level 345 redis-server on

8. Start Redis Server

sudo service redis-server start

Sunday, 19 April 2015

install ruby on rails and nginx on Amazon Linux AMI

1- https://www.digitalocean.com/community/tutorials/how-to-deploy-rails-apps-using-passenger-with-nginx-on-centos-6-5
2- https://gist.github.com/dannguyen/5415628

Friday, 10 April 2015

clear all tables data in one command in ruby on rails

In lib/tasks/dataclear.rake

namespace :dataclear do
  desc "Truncate all tables"
  task :truncate => :environment do
    conn = ActiveRecord::Base.connection
    tables = conn.execute("show tables").map { |r| r[0] }
    tables.delete "schema_migrations"
    tables.each { |t| conn.execute("TRUNCATE #{t}") }
  end
end

Then run "rake dataclear:truncate"

Elasticsearch on Rails

Elasticsearch on Rails, a primer

Elasticsearch is a full text search server powered by Lucene, the Apache Foundation text-search engine used also bySolr.
Elasticsearch is basically a a distributed real-time document store where every field is indexed and searchable, was built to be distributed from the ground up, can be used for real-time analytics, has multi-tenacy, REST API and uses JSON for its query DSL, features that make it quite attractive to developers.

Rails example application

Let’s install the Elasticsearch server on our machine: the project download page has both code and instructions organized in an attractive way, you won’t have any problem with it. If you’re on OSX you can install via homebrew using the following command: brew install elasticsearch
By default the server will run on port 9200, so after starting the service make sure everything is fine runningcurl -X GET http://localhost:9200/ in the terminal.
If everything works as expected we can now create the app and add the gems:

rails new demoapp
cd demoapp
echo "gem 'elasticsearch-rails'" >> Gemfile
echo "gem 'elasticsearch-model'" >> Gemfile
bundle
Create the Article model and populate the db with some data that we will search against later:

rails g model article title:string body:text
rake db:migrate
rails c

hello_world  = Article.create title: 'Hello World', body: 'Lovely day!'
power_search = Article.create title: 'Power Search', body: 'Elasticsearch rules the world!'
(Those variable names will be used later in the examples, so keep them noted).
Let’s include some modules into the Article class to make it searchable:

class Article < ActiveRecord::Base
  include Elasticsearch::Model
  include Elasticsearch::Model::Callbacks
end
Add this line to the top of the app Rakefile to include the handy elasticsearch rake tasks:
require 'elasticsearch/rails/tasks/import'
The new tasks can be listed with bundle exec rake -D elasticsearch.
Remember that in order for old records to be found by elasticsearch we need to import them:
bundle exec rake environment elasticsearch:import:all
We can do the very same thing in the rails console:
Article.import

The search DSL

Let’s play in the rails console making the simplest possible search:
search = Article.search 'world'
This will return an object with class Elasticsearch::Model::Response::Response
If you just need to show data without going through the actual models in the database you can use the resultsmethod, which conveniently wraps the JSON returned by Elasticsearch in ruby objects:

search.results.map { |res| res.title }
# => ["Hello World", "Power Search"]
If you want to see the actual found records, then you just need to call records on that object:
search.records
The above query could be rewritten using Elasticsearch JSON DSL syntax like follows:
Article.search('{"query": {"match": {"_all": "world"}}}').records
Luckily the gem allows us to use both JSON or ruby hash syntax and of course we prefer the latter, don’t we? All the following examples will use ruby hashes.

BOOSTING

The following example uses the caret to give a boost to the title field:

records = Article.search(query: {multi_match: {query: 'world', fields: ['title^10', 'body']}}).records
records.size # => 2
records.first == hello_world # => true
Let’s change the records order boosting the body field instead:

records = Article.search(query: {multi_match: {query: 'world', fields: ['title', 'body^10']}}).records
records.first == power_search # => true

FUZZY SEARCH

When it comes to fulltext search the ability to match mispelled words is mandatory. We can accomplish that easily using the fuzziness param:

records = Article.search(query: {match: {_all: {query: 'wold', fuzziness: 2}}}).records
records.first.title #  => "Hello World"
fuzziness represents the maximum allowed Levenshtein distance, it accepts an integer between 0 and 2 (where 2 means the fuzziest search possible) or the string “AUTO” which will generate an edit distance based on the charachers length of the terms in the query.

CONCLUSIONS

So far we’ve just scratched the surface of Elasticsearch capabilities and complexity, there is so much more to learn: tokenizers, analyzers, indexes, facets, but that’s something far beyond the scope of this short article. I suggest you to go deeper reading the Elasticsearch documentation and the elasticsearch-rails gem readme.

Thursday, 9 April 2015

facebook share button with custom title, description, and image

<a href='http://www.facebook.com/sharer.php?s=100&p[title]=WEB1CHANNEL&p[summary]=Web+Design+Company+in+Dubai.&p[url]=http://www.webchannel.ae&p[images][0]=http://qacode.com/test.jpg'>Facebook Share</a>

In Ruby on Rails:-

<a href='http://www.facebook.com/sharer.php?s=100&p[title]=Your Wellness Room&p[summary]=<%= summary %>&p[url]=<%= @socialshareurl %>&p[images][0]=<%= imageurl %>'><img src="/images/shared/social-feed/shareicon/facebook<%= @socialcolor %>.png" width="12px" height="12px" id="share_button" title="Facebook"> </a>

How to select last record from each day with MySQL

SELECT t1.* FROM personal_measurements t1
  JOIN (SELECT DATE(created_at) date_date, user_id, MAX(created_at) max_date
        FROM personal_measurements
        GROUP BY date_date, user_id
        ) t2
    ON t1.created_at = t2.max_date AND t1.user_id = t2.user_id;