Posts

Showing posts from April, 2015

Devise form within a different controller in rails

Put below methods in application helper then you can call devise form on any controller.  module ApplicationHelper   def resource_name     :user    end   def resource     @resource ||= User.new   end   def devise_mapping     @devise_mapping ||= Devise.mappings[:user]   end end

Installing wkhtmltopdf on Ubuntu Server

apt-get install wkhtmltopdf apt-get install xvfb echo 'xvfb-run --server-args="-screen 0, 1024x768x24" /usr/bin/wkhtmltopdf $*' > /usr/bin/wkhtmltopdf.sh chmod a+rx /usr/bin/wkhtmltopdf.sh ln -s /usr/bin/wkhtmltopdf.sh /usr/local/bin/wkhtmltopdf wkhtmltopdf http://www.google.com output.pdf

permanently “source .rvm/scripts/rvm” in ruby on rails

Put this in your ~/.profile or ~/.bashrc : # This loads RVM into a shell session.     [[ - s "$HOME/.rvm/scripts/rvm" ]] && . "$HOME/.rvm/scripts/rvm" So you don't have to manually type it for every session. And yes it is needed if you want to use rvm

pull and push mysql database

 To Export .sql mysqldump -u [username] -p [database name] > [database name].sql To Import:- mysql -u [username] -p newdatabase < [database name].sql

Connect to mysql on Amazon EC2 from a remote server

Change   /etc/mysql/my.cnf Change   /etc/mysql/my.cnf And It could be that you have not configured the   Amazon Security Group   assigned to your EC2 Instance to accept incoming requests on port 3306 (default port for MySQL). If this is the case then you can easily open up the port for the security group in a few button clicks: 1) Log into you AWS Console and go to 'EC2' 2) On the left hand menu under 'Network & Security' go to 'Security Groups' 3) Check the Security Group in question 4) Click on 'Inbound tab' 5) Choose 'MYSQL' from drop down list and click 'Add Rule' Might not be the reason but worth a go... Once, you are logged in, you need to create a new MySQL user. First, issue the following command to login with the root user  mysql -u root -p If a password is set provide the password and login. Now create a new user with this command create user 'bill'@'%' identified by 'so

Export custom fields in csv file in ruby on rails

  <%= link_to "Export Recipes CSV", download_recipes_path(format: "csv") %> In Controller:-  def download     @recipes = Recipe.order(:name)         send_data @recipes.as_csv ,:filename => 'recipes'   end In Model:-  #For Specific fields   def self.as_csv     CSV.generate do |csv|       csv << [ "Name", "serving_size", "recipe_type", "ingredients", "method", "nutritional_analysis","trainer_id", "recipetags_ids", "description"] ## Header values of CSV       all.each do |recipe|                csv << [recipe.name, recipe.serving_size, recipe.recipe_type, recipe.ingredients, recipe.method, recipe.nutritional_analysis, recipe.trainer_id, recipe.recipetaggings.collect(&:recipetag_id).join(''), recipe.description] ##Row values of CSV       end     end   end      # This will download all the fields of recipe    def self.as_csv      CS

open multiple skype account in ubuntu

Hi Guy, This is the  command to open other skype on same system in ubuntu $ skype --dbpath=~/.Skype2

Edit contents in github pages using prose

Hi Guys, http://prose.io  is the tool to provide github pages editing functionality. To open you github pages for editing you just need to add github username with prefix # like as http://prose.io/# githubusername/

csv file upload progress bar in ruby on rails

Hi Guys, I have added bootstrap progress bar when uploading csv file.  Submit form using Ajax:-        <%= form_for @company, :url=>company_upload_path, :html => {multipart: true,:class=>"upload_form",:remote=>true,:id=>"new_company"} do |f| %>                           <%= file_field_tag "file",:class=>"form-control btn btn-default",:id=>"model_file" %>               <%= f.button 'Import', :class => 'submit  btn btn-primary import_button' %>             <% end %> Add progress-bar div when you want to show progress bar and give its initial width 0. <div class="progress" id = "import-campaign-bar">           <div  class="progress-bar progress-bar-success" style="width: 0%"></div> </div> def company_upload         # @company=Company.import_company(params[:compa

foreman on heroku in ruby on rails

I follow the convention; Procfile defines all processes .foreman set specific foreman variables Development: .env sets environment variables for each developer .env.example sets defaults for development foreman start starts all processes Production: heroku config sets environment variables heroku ps:scale turns on or off whichever processes are needed for production Here's an example from a project. Procfile: web : bundle exec unicorn_rails - p $PORT - c ./ config / unicorn . rb worker : bundle exec rake jobs : work search : bundle exec rake sunspot : solr : run .env.example: # default S3 bucket S3_KEY = keykeykeykeykeykey S3_SECRET = secretsecretsecret S3_BUCKET = myapp - development .env # developer's private S3 bucket S3_KEY = mememememememememe S3_SECRET = mysecretmysecret S3_BUCKET = myapp - development .foreman: # development port is 3000 port : 3000

do not validate attachment in rails

do_not_validate_attachment_file_type :file

searching like facebook tag in autocomplete

<div id="post_content" contenteditable="true" class="post_content_textarea">         </div> <script> var availableTags = <%= raw @users %>;  var availableTags_category = <%= raw @categories %>;    function split(val) {       return val.split(/@\s*/); } function split2(val) {       return val.split(/#\s*/); } function extractLast(term) {     return split(term).pop(); } function extractLast2(term) {     return split2(term).pop(); }   $(".post_content_textarea")   // don't navigate away from the field on tab when selecting an item   .bind("keydown", function(event) {       if (event.keyCode === $.ui.keyCode.TAB && $(this).data("autocomplete").menu.active) {           event.preventDefault();       }   }).autocomplete({       minLength: 0,       source: function(request, response) {           var term = request

search by @ symbol in autocomplete

<div id="post_content" contenteditable="true" class="post_content_textarea">         </div> <script> var availableTags = <%= raw @users %>;    function split(val) {       return val.split(/@\s*/); } function extractLast(term) {     return split(term).pop(); }   $(".post_content_textarea")   // don't navigate away from the field on tab when selecting an item   .bind("keydown", function(event) {       if (event.keyCode === $.ui.keyCode.TAB && $(this).data("autocomplete").menu.active) {           event.preventDefault();       }   }).autocomplete({       minLength: 0,       source: function(request, response) {           var term = request.term,               results = [];           if (term.indexOf("@") >= 0) {                              term = extractLast(request.term);               if (term.length >

Steps to add dynamic tags to a post

Image
Hello, I have creating steps guide to add tags in jekyll with post 1.   Open   http://prose.io/# username 3.  When you nevigate above url then a window will be open where bottom right corner there is a toggle button called "Authorized github". Click this button and enter valid Github username and password. ​ Add tags in post:- 1. click on _posts folder the new page will open like this ​ 1.1 . Here you can edit existing posts or create new posts..suppose you want to edit " 2014-08-21-Seamus Kraft.md " then click on this post.then new page will open like this. ​ 1.2 If you want to add or edit tag then,click on meta data icon ,then view will be change.like this  ​ Here you can change tag,date , Author name,layout etc. 1.3 what ever tag you mentioned here ,those will be show in thinking page. 1.4 You can also put multiple tag you can add multiple tag like this --------- layout: default tags: - open - priva

get linkedin friends list in ruby on rails

Hi i have found solution to how to get linked in friends list using token and secret. First of fall you should must authenticated with linkedin. Put this code where you want to fetch linked in friends.  client = linked_in_client(current_user.authentication) @profile = client.profile  @my_connections = client.connections.all def linked_in_client(detail)     LinkedIn.configure do |config|       config.token = "75keyc3e2w7pyc"       config.secret = "97c1znGyaEJrM8bY"       config.default_profile_fields = ['id', "first-name", "last-name"]     end     linked_in = LinkedIn::Client.new     linked_in.authorize_from_access(detail.token, detail.secret)     linked_in_client ||= linked_in   end

preview and upload image in jquery

<td>Company Logo:<%= file_field_tag :avatar,name: "avatar",:onchange => "showimagepreview(this)",:class=>"img_file" %></td>     <img id="imgprvw" style="width: 167px; height: 94px; margin-top: 8px;" /> <script>   function showimagepreview(input) {     if (input.files && input.files[0]) {     var filerdr = new FileReader();     filerdr.onload = function(e) {     $('#imgprvw').attr('src', e.target.result);     }     filerdr.readAsDataURL(input.files[0]);     }     $('.image_upload').submit();   } </script>

crop image using ajax in ruby on rails with papercrop in bootstrap modal

Hi i have found solution for upload image using ajax and then crop by using papercrop. First you need to configured papercrop gem Then <p><%=link_to "Change Picture","#","data-toggle"=>"modal" ,    "data-target"=>"#myModal"%> </p> <!-- Modal --> <div class="modal fade image_modal" id="myModal" tabindex="-1" role="dialog"    aria-labelledby="myModalLabel" aria-hidden="true">    <div class="modal-dialog">       <div class="modal-content">          <div class="modal-header">             <button type="button" class="close"                data-dismiss="modal" aria-hidden="true">                   &times;             </button>             <h4 class="modal-title" id="myModalLabel">                Upload and Cr

Get gmail contacts usign token in ruby on rails

Hello Everyone, I've find a nice way to fetch the gmail contacts of the person whose token is already present in our database. No gem is required for this, just follow the below steps : Step 1 :  https://console.developers.google.com/  create a new application or select one which is existing, then go to "APIs & auth" on the right tab, there in the sub-options choose "API". Now, you'll find list of API, enable " Contacts API ". Step 2 : In your devise.rb where it is written the keys, write the scope to access the contacts of user. => config.omniauth :google_oauth2,  CLIENT ID  ,  CLIENT SECRET,   { scope: ' https://www.googleapis.com/auth/userinfo.email https://www.googleapis.com/auth/userinfo.profile   https://www.google.com/m8/feeds/&response_type=code '}  Step 3 : Write code in the controller or where you want to fetch the contacts list :  =>       token = current_user.authorization.token

Integrate Elasticsearch in ruby on rails

Initial requirement:-You need to install elasticksearch library into your system sudo apt-get update sudo apt-get install openjdk-7-jre-headless -y ### Check http://www.elasticsearch.org/download/ for latest version of ElasticSearch and replace wget link below # NEW WAY / EASY WAY wget https://download.elasticsearch.org/elasticsearch/elasticsearch/elasticsearch-1.1.1.deb sudo dpkg -i elasticsearch-1.1.1.deb sudo service elasticsearch start #curl http://localhost:9200 Install 3 gems gem "elasticsearch", git: "git:// github.com/elasticsearch/elasticsearch-ruby.git " gem "elasticsearch-model", git: "git:// github.com/elasticsearch/elasticsearch-rails.git " gem "elasticsearch-rails", git: "git:// github.com/elasticsearch/elasticsearch-rails.git " In model:- require 'elasticsearch/model' class Article < ActiveRecord :: Base   include Elasticsearch :: Model   incl

rejex for get number from statement in ruby on rails

/\d\d/.match "This is the 10 number" its will return "10"

Converting MySQL to PostgreSQL

If you working with mysql and loading database with "rake db:structure:load" Then later you want migrate from mysql to postgres then "rake db:structure:load" command will not work with Postgres,you will need to convert sql to postgres Blow are the commands which directly insert .sql file into PG databse then you can create .dump file from postgres which can be use on heroku. Export .sql from mysql mysqldump -u username -p --compatible=postgresql databasename > data.sql Import .sql into Postgres psql -h server -d databasename -U username -f data.sql Then you can create dump file from PG pg_dump databasename > outfile .dump Now you can push this dump file on heroku also. Thanks

Reading Excel Sheets using "Roo" gem in ruby on rails

This gem allows you to read the contents of Open-office spreadsheets (.ods) Excel spreadsheets (.xls) Google (online) spreadsheets Excel's new file format .xlsx How to use this gem : 1) Install            [sudo] gem install roo 2) Create an instance of the excel sheet file                      require 'rubygems'         require 'roo'                 s =  Roo:: Openoffice.new("myspreadsheet.ods")         s =  Roo:: Excel.new(" myspreadsheet.xls ")          s =  Roo:: Google.new(" myspreadsheet_at_google ")         s =  Roo:: Excelx.new(" myspreadsheet.xlsx ")      3)  Reading from a particular sheet of the spreadsheet:      Lets say your spreadsheet has 4 sheets and you want to read the 2nd sheet        s.default_sheet = s. sheets[2]    *  Sheets is an array containing the names of all the sheets inside the spread sheet.     *  If we do not se

Get current method file path

Get current method file path. __FILE__ is a ruby variable which return current file path. Just use : __FILE__

repaire mongodb in ubuntu

sudo rm /var/lib/mongodb/mongod.lock mongod --repair sudo service mongodb start

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;

facebook share button with custom title, description, and image

URLMethod:-   <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>   Feed Method:- <a  id=" hare_button " >Share Facebook</a>  <script>      window.fbAsyncInit = function() {       FB.init({         appId      : 42443434343434334,         xfbml      : true,         version    : 'v2.3'       });     };   

update cron jobs

bundle exec whenever --update-crontab app_name

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"

install ruby on rails and nginx on Amazon Linux AMI

Updating And Preparing The Operating System In order to install Ruby and the other necessary application (e.g. our servers), we need to first prepare the minimally shipped CentOS droplet and equip it with some development tools we will need along the way. Run the following command to update the default tools of your CentOS based droplet: yum -y update # This command will update all the base applications # that come with CentOS by default. Which are mostly # reserved for use by the operating system. Install the bundle containing development tools by executing the following command: yum groupinstall -y 'development tools' # With more recent versions of CentOS, such as 6.5 in our case, # you can simply run: # yum groupinstall -y development # instead. # This bundle of applications contains various tools # Such as: gcc, make, automake, binutils, git etc. Some of the packages we need for this tutorial (e.g. libyaml-devel, nginx etc.) are not found within the off