Friday 2 August 2013

Git Reset Head using Refflog

Refflog is used to reset your HEAD after you had HARD RESET HEAD.

$ install reflog
$ git reflog
$ git reset --hard 4993de0 #(give the HEAD number on which you want to go back)

Useful Links:

Setting up Git to use Diffmerge

Diffmerge is used to manage your merge conflicts cleanly. first you need to download and install Diffmerge. For further configuration
http://adventuresincoding.com/2010/04/how-to-setup-git-to-use-diffmerge/

Restore a postgres database dump

If you want to restore your postgres database from a dump. first cd into the directory where your dump file exist.
Then run the following command in your console.

$ psql -U mypostgresusername -d mydestinationdbname -f mydbdumpfilename.sql


Creating a Postgres admin user

First run this Query on Postgres:

WITH mx AS ( SELECT MAX(id) AS id FROM sch.mytable)
SELECT setval('sch.mytable_id_seq', mx.id) AS curseq
FROM mx; 

Then run this in your console:

$ rake spree_auth:admin:create ?

 

Omni Auth Managing Multiple Providers

Facebook API localhost redirect.

if you are using Omni Auth Facebook and want to redirect to your local host. and you are getting error code 191. It means that your provided redirect URI on facebooks Apps is not correct.
example: http://localhost:3000/   (OR) http://lvh.me:3000/

Authenticate User Using OmniAuth facebook

Here is a step by step Guide Using Omni Auth Facebook. you may encounter some bugs while following the tutorial. Therefore Do not miss to readout the comments of 'Vadym Tyemirov' at the end of the Article. 

Google Omni Auth with devise tutorial

Here is a step by step user guide for using Google Omni Auth with devise.

http://blogs.burnsidedigital.com/2013/03/rails-3-devise-omniauth-and-google/

But one thing I want to add is that, there in section 4, author says that "First, create a new controller called omniauth_callbacks_controller.rb and make it look something like this:" However the code is not given. For that I followed the following link.
https://github.com/plataformatec/devise/blob/master/app/controllers/devise/omniauth_callbacks_controller.rb

Google OmniAuth. Error: redirect_uri_mismatch

If you are using Google OmniAuth with devise and you get this error.

Error: redirect_uri_mismatch

The redirect URI in the request: http://localhost:3000/users/auth/google_oauth2/callback did not match a registered redirect URI.

Copy the highlighted text and Go into the Google developer API where you have registered your App edit sittings and paste it there in the Google redirect URI.

Monday 29 July 2013

Form auto fill using javascript and jquery. Passing and receiving parameters with windows.location

Scenario:

A Signup field with a signup button on index pages. if a user enter their email address and click on signup button it should be redirected to the devise signup path (new). And the email entered on the previous page should be filled in the signup registration form. first you need to override the devise registration form. which is partial.
I resolved the issue by using Javascript and jquery. below are the files I have made changes in.
_________________________________________________

index.html.erb
 
<%= render 'index_signup_label'%>

_________________________________________________

_index_signup_label.html.erb

<div class="signup-label" >
  <div style="margin-bottom: 5px"> <h2>Sign up for free</h2></br>
    <form action="/signup" method="post" id="mc-embedded-subscribe-form" name="mc-embedded-subscribe-form" class="validate" novalidate>
    <input type="email" placeholder="Your best Email" value="" name="EMAIL" class="required email" id="mce-EMAIL">

    <%= button_tag "Free Signup", :id => 'signup-btn', :type => 'button',:class => "button primary" %>
   
</div></br>
    </form>
</div>

<script type="text/javascript">
$('#signup-btn').click(function(){
    var email = $("#mce-EMAIL").val();
    location.href = '<%= signup_path() %>?email='+email;
});

</script>
_____________________________________________

_user_form.html.erb

<p>
  <%= f.label :email, Spree.t(:email) %><br />
  <%= f.email_field :email, :class => 'title uemail', :onChange => 'changeallemail(this.value)', :onfocus => 'resetEl()' %>
</p>


<script type="text/javascript">
function get_param(name){
   if(name=(new RegExp('[?&]'+encodeURIComponent(name)+'=([^&]*)')).exec(location.search))
      return decodeURIComponent(name[1]);
}

$(document).ready(function() {
    var email = get_param('email');
    $('.uemail').val(email);
});
</script>





PHP my admin acccess denied password reset.

ERROR 2002 (HY000): Can't connect to local MySQL server through socket '/var/run/mysqld/mysqld.sock' (2)
$ sudo service mysql start
$ mysql mysql -u root
$ UPDATE user SET password=PASSWORD('newpassword') WHERE user="root";

Restricting a page view to a specific action

Like you have a Nav bar on all pages and you want it to be different on Index Pages.

<div id="subheader" class="<%= 'slider-bg' if (controller_name.eql?('home') && action_name.eql?('index') )%>" >

Can't install RMagick 2.13.2. Can't find Magick-conf

Start working with an existing project

  1. Replace keys in shh Directory
  2. Set username and email
  3. Make a branch
  4. Clone
  5. Create a gemset
  6. Bundle install
  7. Run migration

RVM Commands

$ rvm current
$ rvm install x.y.z (version)
$ rvm use x.y.z
$ rvm use x.y.z@redmine_plugins

Thursday 4 July 2013

Customizing Refinery Page and Menu Titles

if you want to have a separate/different navigation menu title from your page title:
go to pages , edit pages, advanced options give your menu title there.... for SEO purposes browser title, meta keywords and meta description can also b given there.
Reference URL:
http://refinerycms.com/guides/page-titles-and-urls

Refinery adding additional page parts

for all pages if you want to add additional page parts go to config/initializers/refinery/pages.rb
uncomment  # config.default_parts = ["Body", "Side Body"] and add additional page part such as
 config.default_parts = ["Body", "Side Body", "Middle body"]


Changing Page Parts for a single Page

go on to the same part config/initializers/refinery/pages.rb
uncomment and change the following value to true
# config.new_page_parts = false
restart server
now go to your pages tab refinery and edit your home page You’ll notice a plus and minus button at the top right of the visual editor. Click on the plus icon and add a new page part titled “Middle Body” and click save. If you have modified your home.html.erb file, you can use the following snippet to output the new part’s content in your page:
<%= raw @page.content_for(:middle_body) %>

reference URL:
http://refinerycms.com/guides/changing-page-parts

Monday 1 July 2013

Cancan Ability

In your gemfile Include.
1. gem "cancan" 
2. install bundle. 
3. rails g cancan:ability
this will generate an ability class in your models. 
define your Abilities there like below.
but keep remember that you have already defined roles, 
such as you have a User model,
having two roles defined i.e admin and support.

class Ability
include CanCan::Ability
def initialize(user)
user||= User.new
can :read, :all
if user.role == 'admin'
can :manage, :all
else
can :read, :all
end
end
end

4. the resource on which you want to restrict a user,
 use the following filter in their controller.
                  load_and_authorize_resource
5. if you want restrict something in the views not to show.
<% if can? :manage, @flower %>
<td><%= link_to 'Edit', edit_flower_path(flower) %></td>
<% end %>
<% if can? :manage, @flower %>
<td><%= link_to 'Destroy', flower_path(flower),
method: :delete, data: { confirm: 'Are you sure?' } %></td>
<% end %>
 




 


Heroku Push and Assets precompile


  1. git push heroku master
  2. heroku run rake assets:precompile

Using Bootstrap with Rails 3.2

 Useful Resource :

http://railsapps.github.io/twitter-bootstrap-rails.html

Tuesday 25 June 2013

Rails Factory Girl, Stubs and Mocks

Useful Links :

  1. http://stackoverflow.com/questions/5183975/factory-girl-whats-the-purpose
  2. http://stackoverflow.com/questions/5164102/mocks-and-stubs

Michael Hartl tutorial Chapter 7. Error: " expected css "title" with text "Michael Hartl" to return something"

While passing the test for the show method of user, the test fail due to the following error.
Failures:

  1) User pages profile page
     Failure/Error: it { should have_selector('title', text: user.name) }
       expected css "title" with text "Michael Hartl" to return something
     # ./spec/requests/user_pages_spec.rb:18:in `block (3 levels) in <top (required)>'

Finished in 2.22 seconds
33 examples, 1 failure

Failed examples:

rspec ./spec/requests/user_pages_spec.rb:18 # User pages profile page
This is because of the helper tag in "app/views/users/show.html.erb"
 Replace
<% provide(:title, @user.name) %>
with 
 <title><%= @user.name%></title>

Monday 24 June 2013

Static pages should have the right links on the layout

While practising Michael Hartl's Rails tutorial, when I want to test the links. One test is failing with the following error message.
Error: "Static pages should have the right links on the layout
This can be fixed by putting "visit root_path" before  click_link "Sign up now!"
screen shot of the code is given below.
___________________
it "should have the right links on the layout" do
    visit root_path
    click_link "About"
    page.should have_selector 'title', text: full_title('About Us')
    click_link "Help"
    page.should # fill in
    click_link "Contact"
    page.should # fill in
    click_link "Home"
    visit root_path
    click_link "Sign up now!"
    page.should # fill in
    click_link "sample app"
    page.should # fill in
  end
____________________


 Useful Links :

Tuesday 18 June 2013

root access/privileges

go to the root by typing
$ sudo -i
then
# useradd -g root user
then verify with
# id user

Tuesday 14 May 2013

Tuesday 30 April 2013

Rake Routes for a specific controller

rake routes | grep controller_name

Customizing JSON API to return few records

just Add the following method in to the Model ...
def as_json(options = {})
    {
      name: self.name,                # Whatever you want to show
      city: self.city,
      country: self.country,
      customer_id: self.customer_id
   
         }
  end
--------------------------OR---------------------------------------
you can call the .select method in the API controller
like
class Api::V1::YoursController < ApplicationController
  def show
  @your = Your.select('one, two').find(params[:id])
  respond_to do |format|
        format.json {render :json => @your}
        format.xml {render :xml => @your}
    end
 end
end

Rails Restfull API/Rails json/xml api

In Controllers => api => V1
create "users_controllers.rb"
the code inside this controller may seems something like following
class Api::V1::HotelsController < ApplicationController
  def show
  @user = user.find( params[:id] )
  respond_to do |format|
        format.json {render :json => @user}
        format.xml {render :xml => @user}
    end
 end
end
_____
Now go to routes and Add the following
namespace :api do
    namespace :v1 do
      resources :users       
    end
   end
____________
now run $ rake routes | grep users
and check the path against the show method. this will seem something like following.
"/api/v1/users/:id"
---
Now hit http://localhost:3000/api/v1/users/(any ID like 1,2 or 3).json

Monday 29 April 2013

Git History => Git log/push or commit history

$ git log
this will show all the commit history.
but now if someone want to search for specific user commit history
$ git log --author="sami"

creatig a sub branch

first remain on the same branch from where you want to create a sub branch
then run the following command:
$ git checkout -b new_branch

Sunday 28 April 2013

working with console => update attribute

u=User.find(id)
u.update_attribute(:role, 'admin')
u
u.password
u.role
u.status
etc etc

Tuesday 23 April 2013

rails generate add and remove migration

rails generate migration add_and_remove_additional_columns_from_user first_name:string last_name:string

rails production environment

rails s -e production

rails assets precompile

rake assets:precompile

Git changing a Branch

git branch
git checkout 'branch name'

making a directory and cloning

cd ..
ls
rm -rf demoapp/  #(this is for removing the current directory)
mkdir demoapp
git clone git@github.com:xyz-abc/lmk-ror.git . #(github ssh goes here)

Git Commands =++ Git Pull

gitg
git status
git branch
git pull origin branch_name
rails s

Git Changing/Renaming Branch Name

git branch -m newname

Monday 22 April 2013

Github Changing Username

  • Changing username
$ git config --global user.name "givename"
to confirm  run $ git config --global user.name

Thursday 4 April 2013

USEFULL STUDY MATERIAL

Usefull study material for ruby and rails
  1.  Programming Ruby 1.9, The pragmatic programmers guide by Dave thomas with chad fowler and Andy hunt.
  2. Roy Thomas Fielding PhD thesis on "Architectural Styles and the Design of Network-based Software Architectures" (the basic concept of RESTful architecture was presented by Thomas for the first time) ..
  3. SIMPLY RAILS 2, BY PATRICK LENZ
  4. Beginning Rails 3, By Cloves Carneiro Jr., and Rida Al Barazi
  5. The one that I liked the most ...Ruby on Rails 3.0, a free student manual
  6. Agile web development with Rails, Fourth Edition, for Rails 3.2 , free download link
  7. The RSpec Book, behavior driven development with RSpec, Cucumber and Friends By David Chelimsky with Dave Astels, Zach Dennis, Aslak Hellesøy, Bryan Helmkamp and Dan North, free download Link
  8. Another RSpec Book. Better Specs
  9. Learning JavaScript Design Patterns by Addy Osmani. Link 

Rails 3.2 MULTIPLE SERVER ISSUE

rails 3.2 do not allow to run multiple servers to resolve this issue the following command can be used ..

$ bundle exec rails s -p 3001 -P tmp/pids/server2.pid
___________________
Another Solution is to follow the steps below :
  • $ lsof|grep 3000

  • this will give you a line starting with:
                    ruby   3205   sami   8u  IPv4
  • take the number in second position (3205 in this case) 
and in console do:
  • kill -9 6205

RAILS DATABASE IMPORT THROUGH CONSOLE

RAILS DATABASE IMPORT
$ mysql -u root -p db_name < file_name.sql
like
mysql -u root -p xxx_development < data_migrate_xxx.sql