Wednesday, 5 December 2018

switch user -- users list click any user for session create

Please visit the above doc :

https://github.com/flyerhzm/switch_user
======================================

Add Gem:

gem "switch_user"
=======================================
If you need to override the default configuration, run rails g switch_user:install and a copy of the configuration file will be copied to config/initializers/switch_user.rb in your project.

rails g switch_user:install

===========================================

Add file for controller:

app/controllers/switch_user_controller.rb

class SwitchUserController < ApplicationController
  def set_current_user
  user = User.find(params[:scope_identifier])
                # without devise
  if user.present?
  session[:user_id] = user.id
  redirect_to '/'
  end
                # with devise 
  # sign_in(user)
  end

  def remember_user
  end

end

==============================================

config/routes.rb

get 'switch_user', to: 'switch_user#set_current_user'

  get 'switch_user/remember_user', to: 'switch_user#remember_user'


=============================================

Add Link for Button:

1. Activeadmin Users index page
   
     column "Switch User" do |show|
        links = link_to 'Login As', "/switch_user?scope_identifier=#{show.id}"
     end

2. simple rails users index
   
    <%= link_to 'Login As', "/switch_user?scope_identifier=#{user.id}"%>
==============================================








Saturday, 1 December 2018

cookie set and delete on click

Require jquery cookie js:

//= require jquery.cookie.js

$(".module_close").on('click', function() {
    $(".module_hide").addClass('hidden')
    $.cookie('the_cookie', 'hide information');
    console.log($.cookie('the_cookie'))
  });
  $(".fa_info_click").on('click', function() {
    $(".module_hide").removeClass('hidden')
    $.cookie('the_cookie', '');
    console.log($.cookie('the_cookie'))
  });

$(window).on('load',function() {
  if ($.cookie('the_cookie') != ''){
    $(".module_hide").addClass('hidden');
  }
});


html :
.row.wrapper.border-bottom.white-bg.page-heading.module_hide
    a.close.module_close id="hide" data-toggle="tooltip" title="Close" href="#"  ×



Tuesday, 9 October 2018

404 page

Please visit site:

https://mattbrictson.com/dynamic-rails-error-pages

rails generate controller errors not_found internal_server_error
This creates app/controllers/errors_controller.rb with corresponding view templates in app/views/errors/ for the not found (404) and internal server error (500) pages. (Ruby methods declared with def can’t start with numbers, so use the spelled-out error names instead.)

2SEND THE RIGHT STATUS CODES

class ErrorsController < ApplicationController
  def not_found
    render(:status => 404)
  end

  def internal_server_error
    render(:status => 500)
  end
end
Normally Rails sends an HTTP status of 200 OK when it renders a view template, but in this case we want 404 or 500 to be sent according to error page being rendered. This requires a slight tweak to the errors_controller.rb that Rails generates. You don’t need to specify the name of the template to render, because by convention it is the same as the action name.

3CONFIGURE THE ROUTES

match "/404", :to => "errors#not_found", :via => :all
match "/500", :to => "errors#internal_server_error", :via => :all
Rails expects the error pages to be served from /<error code>. Adding these simple routes in config/routes.rb connects those requests to the appropriate actions of the errors controller. Using match ... :via => :all allows the error pages to be displayed for any type of request (GET, POST, PUT, etc.).

4TELL RAILS TO USE OUR ROUTES FOR ERROR HANDLING

config.exceptions_app = self.routes
Add this line to config/application.rb. This tells Rails to serve error pages from the Rails app itself (i.e. the routes we just set up), rather than using static error pages in public/.

5. config/environments/development.rb:
config.consider_all_requests_local = false
























Thursday, 4 October 2018

Login with username

Please visit site:

https://github.com/plataformatec/devise/wiki/How-To:-Allow-users-to-sign-in-using-their-username-or-email-address

Create a migration:

rails generate migration add_username_to_users username:string:uniq

Run the migration:

rake db:migrate
User.rb:

devise :database_authenticatable, :registerable,
         :recoverable, :rememberable, :trackable, :validatable, :confirmable, authentication_keys: [:login]

attr_writer :login

validates :username, presence: :true, uniqueness: { case_sensitive: false }
  validate :validate_username

def login
    @login || self.username || self.email
  end
  def self.find_for_database_authentication(warden_conditions)
    conditions = warden_conditions.dup
    if login = conditions.delete(:login)
      where(conditions.to_h).where(["lower(username) = :value OR lower(email) = :value", { :value => login.downcase }]).first
    elsif conditions.has_key?(:username) || conditions.has_key?(:email)
      where(conditions.to_h).first
    end
  end
  def validate_username
    if User.where(email: username).exists?
      errors.add(:username, :invalid)
    end
  end
=========================================================

Modify config/initializers/devise.rb to have:
config.authentication_keys = [ :login ]

Application.rb

config.exceptions_app = self.routes

Modify the views

sessions/new.html.erb:
  -  <p><%= f.label :email %><br />
  -  <%= f.email_field :email %></p>
  +  <p><%= f.label :login %><br />
  +  <%= f.text_field :login %></p>
Use :login and not :username in the sessions/new.html.erb
registrations/new.html.erb:
  +  <p><%= f.label :username %><br />
  +  <%= f.text_field :username %></p>
     <p><%= f.label :email %><br />
     <%= f.email_field :email %></p>
registrations/edit.html.erb:
  +  <p><%= f.label :username %><br />
  +  <%= f.text_field :username %></p>
     <p><%= f.label :email %><br />
     <%= f.email_field :email %></p>

Configure Devise to use username as reset password or confirmation keys

Simply modify config/initializers/devise.rb to have:
config.reset_password_keys = [ :username ]
config.confirmation_keys = [ :username ]

















Password update

Routes.rb :

resources :users do
    collection do
      patch 'update_password'
    end
  end
  get 'change_password' => "users#change_password"


users_controller.rb :

def change_password
    @user = current_user
  end
  def update_password
    @user = current_user
    unless @user.valid_password?(params[:user][:current_password])
      @user.errors.add(:base, "Current Password is incorrect.")
      return render "change_password"
    end
    if @user.update(user_params)
      # Sign in the user by passing validation in case their password changed
      bypass_sign_in(@user)
      redirect_to root_path
      #redirect_to destroy_user_session_path
    else
      render "change_password"
    end
  end

Monday, 10 September 2018

Bitbucket runing time out error and bitbucket is not open

Open terminal:

run---  nautilus /etc/hosts

open file Sublime text

127.0.0.1 localhost
127.0.1.1 rinku-HP-Notebook

# The following lines are desirable for IPv6 capable hosts
::1     ip6-localhost ip6-loopback
fe00::0 ip6-localnet
ff00::0 ip6-mcastprefix
ff02::1 ip6-allnodes

ff02::2 ip6-allrouters
104.192.143.2 bitbucket.org   ----- this line remove


then save file
Password: system password


https://askubuntu.com/questions/17062/how-to-open-a-directory-folder-and-a-url-through-terminal

Wednesday, 5 September 2018

uploading big image for inginx

Following link:

https://stackoverflow.com/questions/26717013/how-to-edit-nginx-conf-to-increase-file-size-upload

/etc/nginx/nginx.conf

Now that you are editing the file you need to add the line into the server block, like so;
server {
    client_max_body_size 500M;

    //other lines...
}
If you are hosting multiple sites add it to the http context like so;
http {
    client_max_body_size 500M;

    //other lines...
}
And also update the upload_max_filesize in your php.ini file so that you can upload files of the same size.

Thursday, 28 June 2018

Fix hp wifi problem

1. First:

sudo modprobe -rv rtl8723be

sudo modprobe -v rtl8723be ant_sel=2
2. Second:
sudo modprobe -rv rtl8723be
sudo modprobe -v rtl8723be ant_sel=1

Wednesday, 6 June 2018

Devise form anywhere rails

Application controller:-

helper_method :resource_name, :resource, :devise_mapping, :resource_class

  def resource_name
    :user
  end

  def resource
    @resource ||= User.new
  end

  def resource_class
    User
  end

  def devise_mapping
    @devise_mapping ||= Devise.mappings[:user]
  end

Tuesday, 15 May 2018

Redirect back to current page after sign in, sign out

Redirect back to current page after sign in, sign out


Applications_controller.rb


after_filter :store_location


    def store_location
      # store last url - this is needed for post-login redirect to whatever the user last visited.
      return unless request.get?
      if (request.path != "/users/sign_in" &&
          request.path != "/users/sign_up" &&
          request.path != "/users/password/new" &&
          request.path != "/users/password/edit" &&
          request.path != "/users/confirmation" &&
          request.path != "/users/sign_out" &&
          !request.xhr?) # don't store ajax calls
        session[:previous_url] = request.fullpath
      end
    end

    def after_sign_in_path_for(resource)
      session[:previous_url] || root_path 
    end
  def after_sign_out_path_for(resource)
     request.referrer|| root_path
   end

Thursday, 10 May 2018

PREVIEW AN IMAGE AND VIDEO BEFORE IT IS UPLOADED

Please take a look at the sample JS code below:

<script type="text/javascript">
  function readURL(input) {
    if (input.files && input.files[0]) {
    var reader = new FileReader();

    reader.onload = function (e) {
    $('#blah').attr('src', e.target.result);
    }

    reader.readAsDataURL(input.files[0]);
    }
  }

  $("#imgInp").change(function(){
    readURL(this);
  });
</script>


and the associated HTML:


<div class="field">
    <%= form.label :image %>
    <%= form.file_field :image,  id: "imgInp" %>
    <img id="blah" src="#" alt="your image" style="height: 150px; width: 200px;" />
  </div>


================================================================

Preview Video Before Saving



We can follow :-


Sunday, 6 May 2018

Customers should be able to view the venue on a map

application.html.erb

        <head>
 <title>Wedding Rooms</title>
 <%= stylesheet_link_tag    "application", media: "all", "data-turbolinks-track" => true %>
 <%= javascript_include_tag "application", "data-turbolinks-track" => true %>
 <%= csrf_meta_tags %>
</head>


_form.html.erb :-


<script src="https://maps.googleapis.com/maps/api/js?key=AIzaSyAvuPSxdugPS2FJQibo-i78wVZHWgmKemk"
    ></script>
<link href="http://code.jquery.com/ui/1.10.2/themes/smoothness/jquery-ui.css" rel="Stylesheet"></link>
<script src='https://cdn.rawgit.com/pguso/jquery-plugin-circliful/master/js/jquery.circliful.min.js'></script>
<script src="http://code.jquery.com/ui/1.10.2/jquery-ui.js" ></script>

<div class="field">
    <%= f.label :address %><br>
    <%= f.text_field :address,  id: "gmaps-input-address", class: "form-control" %>
    <br>
    <div id="gmaps-canvas"></div>
    <div id="gmaps-error"></div>
    <%= f.hidden_field :latitude, id: "location_latitude" %>
    <%= f.hidden_field :longitude, id: "location_longitude" %>
  </div>

show.htmlerb

                 <% if @product.address.present? %>
<p>
 <strong>Address:</strong>
 <%= @product.address %>
 <div id="map"></div>
</p>
<% else %>
<% end %>


<script type="text/javascript">
setTimeout(function(){
    $(document).ready(function(){
$('.bxslider').bxSlider({
 auto: true,
 autoControls: true,
 stopAutoOnClick: true,
 pager: true,
 slideWidth: 200
});
});
}, 2000);
</script>
<style>
   #map {
    height: 400px;
    width: 100%;
   }
</style>
  <script>
    function initMap() {
    var lat1 = <%= @product.latitude %>;
    var long1 = <%= @product.longitude %>;
      var uluru = {lat: lat1, lng: long1};
      var map = new google.maps.Map(document.getElementById('map'), {
        zoom: 15,
        center: uluru
      });
      var marker = new google.maps.Marker({
        position: uluru,
        map: map
      });
    }
  </script>
  <script async defer
  src="https://maps.googleapis.com/maps/api/js?key=AIzaSyAvuPSxdugPS2FJQibo-i78wVZHWgmKemk&callback=initMap">
  </script>

Migration :-

add_column :products, :latitude, :decimal, {:precision=>10, :scale=>6}
add_column :products, :longitude, :decimal, {:precision=>10, :scale=>6}

Friday, 4 May 2018

Tasks: Need to display mailchimp emails by using API with Pagination


gem 'gibbon'

your_app/config/initializers/gibbon.rb

Gibbon::Request.api_key = "12bfe8bed564a0a4e6b6250baa8f4c51-us14"
Gibbon::Request.timeout = 15
Gibbon::Request.open_timeout = 15
Gibbon::Request.symbolize_keys = true

Gibbon::Request.debug = false

app/controller :-

class HomeController < ApplicationController
  def index
  gibbon = Gibbon::Request.new(api_key: "12bfe8bed564a0a4e6b6250baa8f4c51-us14", debug: true)
  # members = gibbon.lists("5984a13076").members.retrieve
 
  @page = params[:page].present? ? params[:page].to_i : 1
  offset = (@page-1) * 50
  members =  gibbon.lists("5984a13076").members.retrieve(params: {"count": "50", "offset": offset.to_s, "status": "subscribed"})
  @contacts = members.body[:members]
  @total_pages = (members.body[:total_items]/50.0).ceil
  end
end
--------------------------------------------------------------------------------------------------------------------------

Views:-

<div class="row">
            <% @contacts.each do |contact| %>
            <div class="col-sm-3 text-left">
              <a href="mailto:<%= contact[:email_address] %>"><%= contact[:email_address] %></a>
            </div>
            <% end %>
        </div>
        <div class="row pull-right">
            <nav aria-label="Page navigation " >
          <ul class="pagination">
            <% if @page > 1 %>
            <li class="page-item"><a class="page-link" href="/home/index?page=<%=  @page -1%>">Previous</a></li>
            <% end %>
            <% (1..@total_pages).each do |page|%>
            <li class="page-item <%= @page== page ? 'active' : nil %>"><a class="page-link" href="/home/index?page=<%= page %>"><%= page %></a></li>
            <% end %>
            <% if @page < @total_pages%>
            <li class="page-item"><a class="page-link" href="/home/index?page=<%=  @page +1%>">Next</a></li>
            <% end %>
          </ul>
        </nav>
        </div>
-------------------------------------------------------------------------------------

<style type="text/css">
.pull-right{float: right;}
</style>