Hexa's Blog

Rails, How to set redirect path after devise updating password

22/12/2015 Rails

This post is all about how to change redirect url after devise update password (or any?). By default, devise after change password successfully, it will redirect to the root url. There are step you have to do to change the redirect path.

  1. Make devise controllers Or generate using command rails g devise:controllers user

  2. After generating, because I want to change the redirect url after changing password. The only file I concern is passwords_controller.rb, the method you have to override is after_resetting_password_path_for, within this method, you have to declare your favorite redirect url.

for example:

class User::PasswordsController < Devise::PasswordsController
  protected
  def after_resetting_password_path_for(resource)
    change_password_success_path
    #OR "http://google.com"
  end
end

Rails, configuring view path of controller

22/12/2015 Rails

This is a solution to configure the view path of any controller in Rails web framework. The only method you have to concern is self.controller_path

class User::HomeController < ApplicationController
  def self.controller_path
    "users/home"
  end
end

With this configuration, all view of User::HomeController will be located in app/users/home/

How to add new public directory in Phoenix framework

15/12/2015 Phoenix

In Phoenix web framework, there is a share directory /priv. By default, it will only public css,js,images,fonts directory. However, If you want to share a new directory to save upload image for example, you have to end_point file at

/lib/app_name/end_point.ex . Look at plug Plug.Static, the only: macro declares which directory, files could be public. Simply, you have to append your directory name at only:line.

This is my configuration to add a directory named avatar public. This directory is under /priv/static.

plug Plug.Static,
    at: "/", from: :blog_phoenix, gzip: false,
    only: ~w(avatars css fonts images js favicon.ico robots.txt)
    ### Other no need configuration
end

Your tree should look like below

priv
├── repo
│   ├── migrations
│   └── seeds.exs
└── static
    ├── avatars
    │   ├── abc.text
    │   ├── Screenshot\ from\ 2015-12-04\ 22-31-39.png
    │   ├── Screenshot\ from\ 2015-12-11\ 01-49-29.png
    │   └── Screenshot\ from\ 2015-12-14\ 22-21-56.png
    ├── css
    │   ├── app.css
    │   └── app.css.map
    ├── favicon.ico
    ├── images
    │   └── phoenix.png
    ├── js
    │   ├── app.js
    │   └── app.js.map
    └── robots.txt

Rails, how to export excel files

07/12/2015 Ruby on Rails 4

On the front-end, instead of using Ajax(post, get). I uses window.location

$("#export-quote-button").click(function(){
  var encoded = $.param(getQuoteParams(), true);
  var url = "/quotes/tran_stats/export_search_result?" + encoded;
  window.location = url;
});

On the back-end, I uses a gem named spreadsheet

def export_search_result
    require 'spreadsheet'
    require 'stringio'
    Spreadsheet.client_encoding = 'UTF-8'
    book = Spreadsheet::Workbook.new
    sheet1 = book.create_worksheet
    #YOUR DATA PROCESSOR HERE
    file_name = "abc.xls"
    spreadsheet = StringIO.new
    book.write spreadsheet
    send_data(spreadsheet.string, :filename => file_name,
              :type => "application/vnd.ms-excel")
end

Comparison of LinkList,Tuples, Maps, HashDict and Keyword Comparison in Elixir

01/12/2015 Elixir

1. Tuples It’s an order collection of values. There is a tip for using Tuples, a typical tuples has two to four elements

  • Once created, a tuples cannot be modified, the only thing we can do is matching(assigning) variable with new tuple.
  • If the number of tuple element is great,(probably greater than 4 elements), programmer should use Map

2. List (LinkList) The list of Elixir is link-list, there are some features/specification that you should noted.

  • It is easy to travel from head to tail, but expensive to get to particular element for example a[22]. You will have to loop via 21 elements.
  • It’s easy to add an new element to a link-list to the head or tail.

3. Keyword List Keyword list is a list of tuples of pair values. An example below explain the keyword list.

[name: "Linh", age: 2]
[{:name, "Linh}, {:age, 2}]
  • Keyword list allows duplicated key value, because in fact, it’s a list

4. Map Map is used to save collection with a pair of key and value. Unlike keyword list, Map does not allow duplicated keys. Accessing a map by:

states = %{ "AL" => "Alabama", "WI" => "Wisconsin" }
states["AL"]

Excel file, replace special character single quotes which besides numbers

27/11/2015 etc

I have work with spreadsheet gem on ruby, Sometime I do realize that in the LibreOffice, the content is something like '24%, the character single quote refers to a string. However, I want a number instead. A possible way to convert them without programming is Find and Replace. However it does not easy as I say because the character ' is a special character in LibreOffice, you have to use regular expression to work with this.

There is a solution to convert string to number in such case is using replace function name Find and Replace C-h in LibreOffice. In the Search for text, type ^.; in the Replace with, type $. In the other options, please tick on Regular expressions. Finally, you can choose replace or replace all.

Elixir Cheatsheet

20/11/2015 cheatsheet

This is cheatsheet for Elixir, it’s a not a summary of this language, this article all about tweak, remember note for Elixir language.

1. For loop Given that, we we a list of map

people = [
  %{name: "Linh", age: 22},
  %{name: "Son", age: 18},
  %{name: "Long", age: 15},
]
for person <- people, do: (
  IO.inspect person
)

Elixir supports a for conditional loop.

for person = %{age: tuoi}<- people, tuoi < 20, do: (
  IO.inspect person
)

2. Update a map

old_map = %{attr1: 1, attr2: 2 }
new_map = %{old_map | attr1:  3}

3. Struct Generate Struct

defmodule Subscriber do
  defstruct name: "", paid: false, over_18: true
end

sub1 = %Subcriber{}
sub2 = %Subcriber{name: "sub2", paid: true, over_18: false}

Use Struct attribute

sub1.name
sub2.name
sub2[:name]

Update attr in a struct

sub2 = %Subcriber{name: "sub2", paid: true, over_18: false}
sub2 = %{sub2 | name: "Another sub2"}

#alternative solution:
put_in(sub2.name, "new_name")

JavaScript, rounding number after decimal

30/09/2015 etc

Given that, you have to work with many decimal number for example: 0.335, 0.345, 0.2, 96.6666. And then you want to round those number 2 digits after decimal. The most general way is to used toFix(). However, the behavior of toFix() is not good. Let test with value 0.335 and 0.345.

0.335.toFix(2) --> 0.33, we expected 0.33
0.345.tiFix(2) --> 0.35, we expected 0.34 FAIL!!!

The better solution is that, we try to use the first two digit after decimal, the only issue is that, these two digit up/down are depend on the third digit, perhaps the fifth one. Number 44 is to solve this issue. Any number x.a-b-c-d which has c-d >= 56, the b will be round up by one.

var num = 0.335
var numX10000 = num * 10000;  --> 3350
var Math.floor((numX10000 + 44) / 100) --> 3350 + 44 = 3394, floor of 3394/100 = 33

var num = 0.345
var numX10000 = num * 10000;  --> 3450
var Math.floor((numX10000 + 44) / 100) --> 3450 + 44 = 3494, floor of 3494/100 = 34

A good solution come up with a compact function which can help you use in any time.

function long_round_number(number, digit){
  var multiplier = Math.pow(10, digit + 2);
  var multiple_number = Math.floor(number * multiplier)
  var roundup_number = multiple_number + 44;
  var return_value = Math.floor(roundup_number / 100) / Math.pow(10, digit)
  return return_value;
}

function roundNumber(number, digit){
  var multiplier = Math.pow(10, digit + 2);
  var new_number = Math.floor(multiplier * number) + 44;
  return  Math.floor(new_number / 100) / Math.pow(10, digit);
}

Add new methods to exist resource routes as collection in Rails

10/09/2015 Ruby on Rails 4

Rails does support built-in CRUD with RESTful. It provides default url for developers. However, there could be a time that developer want to add more method/action to work with exist routes. Hence, this is solution.

This is a default setting for resources of pictures

resources :pictures

This is modification with new upload method which use GET protocol.

resources :pictures do
  collection do
    get 'upload', to: 'pictures#upload'
  end
end

Chrome, Firefox, Conkeror redirecting to advertise websites

01/09/2015 etc

My browsers always automatically redirect to advertise website. That’s a pain in my ass. In particular, While I am reading software API, it change my current pages to another ad pages. Seemingly, someone did change my default dns to advertise dns server.

1. Change the DNS Set the current dns to google dns: 8.8.8.8, 8.8.4.4

2. Reset the Network Manager

sudo systemclt restart NetworkManager

After finished this step, firefox should work well

3. Remove cache in Google Chrome

## Go to ~/.cache/google-chrome
cd ~/.cache/google-chrome/Default
## remove file in Cache directory
rm Cache/*
## remove file in Media Cache directory
rm Media\ Cache/*

4. Remove cached in Conkeror

## move to dir of conkeror cache
cd ~/.cache/conkeror.mozdev.org/conkeror
## remove all cached
rm -rf *