Posts

Drag and drop ordering in rails

Add order_number column into news table:-  rails g migration add_order_number_to_news order_number:integer In config/routes.rb     get '/news_ordering/(:id)' => 'news#news_ordering', as: :news_ordering    post  '/re_order_news'                              => 'news#re_order_news' In app/views/news/news_ordering.html.erb   <style>   #sortable {      list-style-type: none;     margin: 0;      width: 60%;     cursor: pointer;   }   .pic_box {     border: 1px #cccccc solid;      padding: 2%;     margin: 1%;      width: 50%;   }   .img_box{     height: 60px;     width: 60px;   } </style> <div class="wrapper wrapper-content animated fadeInRight">     <p id="notice"><%= notice %></p>     <div class="row">         <div class="col-lg-12">             <div class="ibox float-e-margins">    

Order items by Drag and drop in ruby on rails

Add order_number column into news table:-  rails g migration add_order_number_to_news order_number:integer In config/routes.rb    get '/news_ordering/(:id)' => 'news#news_ordering', as: :news_ordering    post  '/re_order_news'                              => 'news#re_order_news' In app/views/news/news_ordering.html.erb   <style>   #sortable {      list-style-type: none;     margin: 0;      width: 60%;     cursor: pointer;   }   .pic_box {     border: 1px #cccccc solid;      padding: 2%;     margin: 1%;      width: 50%;   }   .img_box{     height: 60px;     width: 60px;   } </style> <div class="wrapper wrapper-content animated fadeInRight">     <p id="notice"><%= notice %></p>     <div class="row">         <div class="col-lg-12">             <div class="ibox float-e-margins">      

Drag and drop ordering in rails

Add order_number column into news table:-  rails g migration add_order_number_to_news order_number:integer In config/routes.rb     get '/news_ordering/(:id)' => 'news#news_ordering', as: :news_ordering    post  '/re_order_news'                              => 'news#re_order_news' In app/views/news/news_ordering.html.erb   <style>   #sortable {      list-style-type: none;     margin: 0;      width: 60%;     cursor: pointer;   }   .pic_box {     border: 1px #cccccc solid;      padding: 2%;     margin: 1%;      width: 50%;   }   .img_box{     height: 60px;     width: 60px;   } </style> <div class="wrapper wrapper-content animated fadeInRight">     <p id="notice"><%= notice %></p>     <div class="row">         <div class="col-lg-12">             <div class="ibox float-e-margins">      

Get Fitibt Access token bu oauth2 authentication.

Get the code by setting up omniauth callback URL:- redirect_to "https://www.fitbit.com/oauth2/authorize?response_type=code&client_id=#{ENV['FITBIT_CLIENT_ID']}&redirect_uri=#{$URL}%2Fauth%2Ffitbit_oauth2%2Fcallback%2F&scope=activity%20heartrate%20location%20nutrition%20profile%20settings%20sleep%20social%20weight&expires_in=604800" You will get code in params[:code], then use this code in following script;- uri = URI.parse("https://api.fitbit.com/oauth2/token")         http = Net::HTTP.new(uri.host, uri.port)         http.use_ssl = true         request = Net::HTTP::Post.new(uri.request_uri)         header_string =  Base64.encode64(("#{ENV['FITBIT_CLIENT_ID']}:#{ ENV['FITBIT_CONSUMER_SECRET']}"))         request.set_form_data('clientId' => ENV['FITBIT_CLIENT_ID'], 'grant_type' => 'authorization_code', 'redirect_uri' => $URL + '/auth/fitbit_oauth2/c

Add Ruby slim package into Sublime text editor

The simplest method of installation is through the Sublime Text console. The console is accessed via the  ctrl + `  shortcut or the  View  >  Show Console  menu. Once open, paste the appropriate Python code for your version of Sublime Text into the console. Sublime-3 import urllib.request,os,hashlib; h = '2915d1851351e5ee549c20394736b442' + '8bc59f460fa1548d1514676163dafc88'; pf = 'Package Control.sublime-package'; ipp = sublime.installed_packages_path(); urllib.request.install_opener( urllib.request.build_opener( urllib.request.ProxyHandler()) ); by = urllib.request.urlopen( 'http://packagecontrol.io/' + pf.replace(' ', '%20')).read(); dh = hashlib.sha256(by).hexdigest(); print('Error validating download (got %s instead of %s), please try manual install' % (dh, h)) if dh != h else open(os.path.join( ipp, pf), 'wb' ).write(by) Sublime- 2 import urllib2,os,hashlib; h = '2915d1851351e5ee549c20394736b442'

Create user in postgresql and connect it into rails application

Install Postgresql:- sudo sh -c "echo 'deb http://apt.postgresql.org/pub/repos/apt/ precise-pgdg main' > /etc/apt/sources.list.d/pgdg.list" wget --quiet -O - http://apt.postgresql.org/pub/repos/apt/ACCC4CF8.asc | sudo apt-key add - sudo apt-get update sudo apt-get install postgresql-common sudo apt-get install postgresql-9.5 libpq-dev   The postgres installation doesn't setup a user for you, so you'll need to follow these steps to create a user with permission to create databases. Feel free to replace arvind with your username. sudo -u postgres createuser arvind -s  # If you would like to set a password for the user, you can do the following  sudo -u postgres psql postgres=# \password arvind   Come into Rails Application config/database.yml default: &default adapter: postgresql pool: 5 username: 'arvind' password: 'arvind' timeout: 5000 host: 127.0.0.1 development: <<: *default database: db_developm

show loader on ajax start

In HTML:- <div class="ajax-loading">     <span>       <p id="please_wait"><strong>Please wait..</strong></p>       <p><i class="glyphicon glyphicon-refresh gly-spin" aria-hidden="true">       </i></p>     </span>   </div> <script>        $(document).ajaxStart(function() {              $(".ajax-loading").show();     });     $(document).ajaxStop(function() {          $(".ajax-loading").hide();     }); </script> In CSS:- /* Loading css*/ div.ajax-loading{   width: 100%;   height: 100%;   top: 0px;   left: 0px;   position: fixed;   display: none;   background: rgba(51,51,51,0.9);   z-index: 2000;   text-align: center;   color: #ffffff; } div.ajax-loading span{   position: absolute;   top: 40%;   left: 50%;   margin-left: -15px; } div.ajax-loading span p{   padding-top: 10px;   padding-right: 10px;   font-size: 1.1em; } div.ajax-loading sp

install wkhtmltopdf on AWS .ebextensions

Add following lines into app_directory/.ebextensions/ruby.conf commands:   # install WKHTML   03_command:     command: yum install xz urw-fonts libXext openssl-devel libXrender   04_command:     command: wget http://download.gna.org/wkhtmltopdf/0.12/0.12.3/wkhtmltox-0.12.3_linux-generic-amd64.tar.xz   05_command:     command: tar -xJf wkhtmltox-0.12.3_linux-generic-amd64.tar.xz   06_command:     command: cp wkhtmltox/bin/wkhtmltopdf /usr/local/bin/wkhtmltopdf   07_command:     command: cp wkhtmltox/bin/wkhtmltoimage /usr/local/bin/wkhtmltoimage

Add Policy on AWs s3 bucket

1. Go to the Bucket properties. 2. Then click on to the Permissions tab. 3. Then click on Edit bucket Policy. 4. Then copy and paste below code into area. {     "Version": "2012-10-17",     "Statement": [         {             "Sid": "AddPerm",             "Effect": "Allow",             "Principal": "*",             "Action": "s3:GetObject",             "Resource": "arn:aws:s3::: cdn.example.com/* "         }     ] }

Configured s3 cmd and upload directory on to S3 bucket

Import S3tools signing key:   wget -O- -q http://s3tools.org/repo/deb-all/stable/s3tools.key | sudo apt-key add -  A dd the repo to sources.list:   sudo wget -O/etc/apt/sources.list.d/s3tools.list http://s3tools.org/repo/deb-all/stable/s3tools.list R efresh package cache and install the newest s3cmd:  sudo apt-get update && sudo apt-get install s3cmd   s3cmd --configure New settings: 2 Access Key: [your access key] 3 Secret Key: [your securet key] 4 Encryption password: somepassword 5 Path to GPG program: /usr/bin/gpg 6 Use HTTPS protocol: False 7 HTTP Proxy server name: 8 HTTP Proxy server port: 0 9 Test access with supplied credentials? [Y/n] Y 10 Please wait... 11 Success. Your access key and secret key worked fine :-) 12 13 Now verifying that encryption works... 14 Success. Encryption and decryption worked fine :-) 15 Save settings? [y/N] y   s3cmd sync s3://acc1_bucket/folder/ s3://acc2_bucket/folder --recursive  

Move dns from Godaddy to AWS route53

1. Login on your aws console; Click on Route 53; Create Hosted Zone; Select your new created host title and click "Go to Record Sets", take note of the nameservers; 2.Login on your Godaddy account; Select your domain; Go to Nameservers and click SetNameservers; paste all the four you took from "Go to Record Sets" Route 53; 3. Now you can set new Cname or Arecord set in AWS Routes53

Get Facebook friends by Json request in Ruby on Rails

Below is the code to return all your facebook friends by passing oauth token:- response = Net::HTTP.get_response(URI("https://graph.facebook.com/v2.5/me/friends?access_token=#{oauth_token)}"))       unless response.is_a?(Net::HTTPSuccess)         return nil       end       json = ActiveSupport::JSON.decode(response.body)       json['summary']['total_count'].to_s  + ' Friends'

get facebook firends list clount by javascript SDK

<script>   // This is called with the results from from FB.getLoginStatus().   function statusChangeCallback(response) {     console.log('statusChangeCallback');     console.log(response);     // The response object is returned with a status field that lets the     // app know the current login status of the person.     // Full docs on the response object can be found in the documentation     // for FB.getLoginStatus().     if (response.status === 'connected') {       // Logged into your app and Facebook.         FbPostAPI();     } else if (response.status === 'not_authorized') {       // The person is logged into Facebook, but not your app.       document.getElementById('status').innerHTML = 'Please log ' +         'into this app.';     } else {       // The person is not logged into Facebook, so we're not sure if       // they are logged into this app or not.       document.getElementById('status').innerHTML = 'Pl

Run sidekiq in proudction mode

##To Update cron bundle exec whenever --update-crontab ## To start Redis redis-server ##clear rediscache redis-cli flushall ## To Start Sidekiq in production env bundle exec sidekiq -d -L sidekiq.log -q mailer,5 -q default -e production ## compile assets rake assets:precompile RAILS_ENV=production

ActionCable Devise Authentication

ActionCable is a new framework for real-time communication over websockets and it will be part of Rails 5. I am not going to get into too much detail about it, you can read the very detailed readme of the project on this link: ActionCable . The websockets server is running in a separate process from the main Rails application which means you need to authenticate your users there too. In the example app , David used a simple cookie based authentication in the app itself and re-validated the cookie at the websocket connection. This is good for demonstration, but many of the Rails based apps are using Devise for authentication so I want to share, how I solved the authentication with Devise. The websocket server doesn't have a session, but it can read the same cookies as the main app, so I figured, I will just set a cookie with the user id and verify that at the socket connection. To do this, I used a Warden hook: # app/config/initializers/warden_hooks.rb Warden ::

Conver mysql .sql file in to postgreql .psql

1. mysqldump --compatible=postgresql --default-character-set=utf8 -r marketacreative.mysql -u root marketacreative 2. python db_converter.py marketacreative.mysql marketacreative.psql Get db_converter.py from https://github.com/lanyrd/mysql-postgresql-converter 3. psql -U root -h localhost -d marketacreative -f  marketacreative.psql  

Install development library in ubuntu

sudo apt - get install libgmp3 - dev

New gem not installing on server

bundle install --path vendor/bundle bundle package --all

has_many association with polymorphic in ruby on rails

rails g model member user_id:integer  invitable_id:integer invitable_type:string class Member < ActiveRecord::Base     belongs_to :user     belongs_to :invitable, polymorphic: true end User can join many communities, groups and meeting rooms, so the has many polymorphic association will look like as:- class User < ActiveRecord::Base   has_many :members, dependent: :destroy   has_many :community_members, through: :members, source: :invitable, source_type: 'Community'   has_many :group_members, through: :members, source: :invitable, source_type: 'Group'   has_many :meeting_rooms_members, through: :members, source: :invitable, source_type: 'MeetingRoom'   has_many :meeting_rooms, dependent: :destroy end

remove html tags from html

html = ' <b><a href="http://foo.com/">foo</a></b><img src="bar.jpg"> '   ActionView :: Base . full_sanitizer . sanitize ( html )