Pages

Thursday, May 1, 2014

Ruby remove duplicate entries in array of hashes but based on more than one value

Suppose you have the following array of hashes:

new_tracks = [{:name=>"Yes, Yes, Yes", :artist=>"Some Dude", :composer=> 'First Dude', :duration=>"3:21"},
 {:name=>"Chick on the Side", :artist=>"Another Dude", :duration=>"3:20"},
 {:name=>"Luv Is", :duration=>"3:13"},
 {:name=>"Yes, Yes, Yes", :artist=>"Some Dude", :composer=> 'First Dude', :duration=>"2"},
 {:name=>"Chick on the Side", :artist=>"Another Dude"}]

uniq accepts a block. If a block is given, it will use the return value of the block for comparison.
You can join the attributes you want into a string and return that string.

new_tracks.uniq { |track| [track[:name], track[:artist]].join(":") }

The resultant of above code will be an array of hashes unique on the basis of name and artist attributes.

Wednesday, April 30, 2014

Configure Authlogic to log in with “username” OR “email”



Its very simple to implement Authlogic to use multiple attributes for login.

For example if you want to enable user to login with either email or username, you just need to add the following things to your code:

class UserSession < Authlogic::Session::Base 
  find_by_login_method :find_by_username_or_email
end
and in user.rb
def self.find_by_username_or_email(login)
  User.find_by_username(login) || User.find_by_email(login)
end

Thursday, April 24, 2014

How to change root password of Mysql to an empty one or blank?


You should first restart the MySQL server or run the following command:
FLUSH PRIVILEGES;
 Now change the root password to an empty one:
mysqladmin -u root -p'<current password>' password ''
Now your password is updated to blank.

Fix String Encoding error with Mysql



The reason was apparently that the database (and especially the database tables) had the wrong character set. Switching the collation of the database alone did not help. Inspection of the database tables showed that each table still had the latin1 charset, which can not store all utf8 characters:
mysql> show table status;
+----------+--------+-------------------+ ..
| Name     | Engine | Collation         | ..
+----------+--------+-------------------+ ..
| my_table | InnoDB | latin1_swedish_ci | ..
Therefore I altered the character set of the table directly:
ALTER TABLE my_table CONVERT TO CHARACTER SET utf8;
Then it finally worked, and the character set is how utf8
   mysql> show table status;
    ... +-------------------+ ..
    ... | Collation         | .. 
    ... +-------------------+ ..
    ....| utf8_general_ci   | ..