Friday, May 3, 2013

Replacing –, ’, etc with UTF-8 Characters in Ruby on Rails

It was getting cumbersome to update these non-utf8 compatible characters time to time!

substitutions = []
substitutions << ['…', '…']           # elipsis
substitutions << ['–', '–']           # long hyphen
substitutions << ['’', "'"]           # curly apostrophe
substitutions << ['“', '"']           # curly open quote

klasses = {'Class1' => [:field1, field2], 'Class2' => [:field1, :field2]}
  
klasses.each_pair do |klass, fields|
  klass = klass.constantize
  klass.all.each do |obj|
    fields.each do |field|
      if obj.send(field).present?
        substitutions.each do |set| 
          obj.send(field.to_s + '=', obj.send(field).gsub(set[0], set[1]))
        end
      end
    end
    
    # Don't fire callback
    klass.skip_callback(:save, :after,  :do_after_save_tasks)
    obj.save!
    
  end
end

Friday, April 26, 2013

How to put aptana launcher on Ubuntu dock

1. Create a file namely aptana3.desktop having:

#!/usr/bin/env xdg-open

[Desktop Entry]
Version=1.0
Type=Application
Terminal=false
StartupNotify=true
Name[en_US]=Aptana Studio 3
Icon=/home/moin/Aptana\ Studio\ 3/icon.xpm
Name=Aptana
Comment=Aptana\ Studio\ 3
Exec=env UBUNTU_MENUPROXY=0 /home/moin/Aptana\ Studio\ 3/AptanaStudio3 -application com.aptana.commandline.launcher.LauncherApplication "$@" > /dev/null 2>&1 &
Categories=Development;IDE;


2. Make it executable

chmod +x /path/of/aptana3.desktop

3. Drag and drop to dock. Right click and lock to dock.

Monday, April 15, 2013

POST RAW JSON request with Basic Auth using Chrome Advance REST client

I was wondering how to POST a RAW JSON request with Basic Authentication for Advance REST client. I tried several permutation and combination and finally came up with exact way.



Notes:
1. Somehow single quote did not worked for me.
2. Json in rails way( => ) would work.
3. user = {...} will work on www-form-url-encoded but not with json.

You might be getting JSON parse error even before request reach to controller!

Thursday, March 28, 2013

Write Rails3 gem


= Introduction
Creating Ruby gems has always been a bit of a pain. When you get right down to it, it's not a hard thing to do, but it's easy to forget how if you don't do it often enough. There are quite a few gems to help you write other gems, but if you're using Rails 3, there's already a gem on your system that does this: Bundler.

It will also generate a stub gem project for you, complete with Rakefile and directory structure.
The Rakefile is fully featured, and will create gem packages and publish them on RubyGems.org.

= Start
have account on github and rubgems.org

= Install bundler to manage building the gem
gem install bundler

= Create the initial gem layout
bundle gem iprocessor

~/workspace$ bundle gem ilinks
      create  iprocessor/Gemfile
      create  iprocessor/Rakefile
      create  iprocessor/LICENSE.txt
      create  iprocessor/README.md
      create  iprocessor/.gitignore
      create  iprocessor/iprocessor.gemspec
      create  iprocessor/lib/iprocessor.rb
      create  iprocessor/lib/iprocessor/version.rb
bundle gem not only generate stub but also initialized Github Repo if you have Git configured already.

The bundle command also generated a Rakefile. This Rakefile is where you'll package and publish your gem. If you look in this file, you'll see that the actual tasks are buried in Bundler's code, but you can run a quick rake -T to get a list of tasks.

~/workspace/iprocessor$ rake -T
rake build    # Build ilinks-0.0.1.gem into the pkg directory
rake install  # Build and install iprocessor-0.0.1.gem into system gems
rake release  # Create tag v0.0.1 and build and push iprocessor-0.0.1.gem to Rubygems

rake -T is self explanatory.

= Ddit ilinks.gemspec

# -*- encoding: utf-8 -*-

lib = File.expand_path('../lib', __FILE__)
$LOAD_PATH.unshift(lib) unless $LOAD_PATH.include?(lib)
require 'iprocessor/version'
require 'iprocessor/conf'

Gem::Specification.new do |gem|
  gem.name          = "iprocessor"
  gem.version       = Iprocessor::VERSION
  gem.authors       = ["Moin Haidar"]
  gem.email         = ["moinhaidar@gmail.com"]
  gem.description   = %q{ Ruby Wrapper for Card Reader API }
  gem.summary       = %q{ Ruby Wrapper for Card Reader API }
  gem.homepage      = ""

  # ensures that any files tracked in the git repo will be included.
  gem.files         = `git ls-files`.split($/)
  gem.executables   = gem.files.grep(%r{^bin/}).map{ |f| File.basename(f) }
  #Files that are used for testing the gem. Supports TestUnit, MiniTest, RSpec, and Cucumber
  gem.test_files    = gem.files.grep(%r{^(test|spec|features)/})
  #Directories within the gem that need to be loaded in order to load the gem.
  gem.require_paths = ["lib"]
  #Specify any dependencies here
  gem.add_dependency 'httparty'
 
end

= Commit to the git repo
git add .
git push origin master

= Setup an .rvmrc for the directory
vim .rvmrc
rvm 1.9.3@iprocessor --create

= Install the gem
- To install in current gemset
rake install

- To install elsewhere
cd path_of_rails_app
rake build
gem install ../gemname/pkg/gemname

Note: Modification does not reflect when you build and install unless you stage it.

= rake release
Make sure to push the changes before release and change the version on further release to avoid error "This tag has already been committed to the repo."

~/workspace/iprocessor$ rake release
iprocessor 0.0.2 built to pkg/iprocessor-0.0.2.gem
Tagged v0.0.2
Pushed git commits and tags
Pushed iprocessor 0.0.2 to rubygems.org

Tuesday, February 19, 2013

An error occurred while installing pg (0.14.1), and Bundler cannot continue

Using 'pg' gem and getting mentioned error?

Grab these packages first:


sudo apt-get install postgresql
sudo apt-get install libpq-dev

Now Go for bundle or gem install pg

Monday, February 18, 2013

An error occurred while installing memcached (1.4.6), and Bundler cannot continue


Memcached needs following packages in order to install memcached gem.

Install the dependent packages:

apt-get install libmemcached-dev libsasl2-dev
apt-get install memcached

Now bundle or get it directly:

sudo gem install memcached –no-rdoc –no-ri

Test:

moin@haidar:~/workspace/kloud$ memcached -p 11211 &
[1] 29573
moin@haidar:~/workspace/kloud$ irb
1.9.3p385 :001 > require 'rubygems'
 => false 
1.9.3p385 :002 > require 'memcached'
 => true 
1.9.3p385 :003 >  $cache = Memcached.new("localhost:11211")
 => #, @options={:hash=>:fnv1_32, :no_block=>false, :noreply=>false, :distribution=>:consistent_ketama, :ketama_weighted=>true, :buffer_requests=>false, :cache_lookups=>true, :support_cas=>false, :tcp_nodelay=>false, :show_backtraces=>false, :retry_timeout=>30, :timeout=>0.25, :rcv_timeout=>0.25, :poll_timeout=>0.25, :connect_timeout=>4, :prefix_key=>"", :prefix_delimiter=>"", :hash_with_prefix_key=>true, :default_ttl=>604800, :default_weight=>8, :sort_hosts=>false, :auto_eject_hosts=>true, :server_failure_limit=>2, :verify_key=>true, :use_udp=>false, :binary_protocol=>false, :credentials=>nil, :experimental_features=>false, :exception_retry_limit=>5, :exceptions_to_retry=>[Memcached::ServerIsMarkedDead, Memcached::ATimeoutOccurred, Memcached::ConnectionBindFailure, Memcached::ConnectionFailure, Memcached::ConnectionSocketCreateFailure, Memcached::Failure, Memcached::MemoryAllocationFailure, Memcached::ReadFailure, Memcached::ServerEnd, Memcached::ServerError, Memcached::SystemError, Memcached::UnknownReadFailure, Memcached::WriteFailure, Memcached::SomeErrorsWereReported]}, @default_ttl=604800, @not_found=#, @not_stored=#
1.9.3p385 :004 > target = {:first => 'Moin', :last => 'Haidar'}
 => {:first=>"Moin", :last=>"Haidar"} 
1.9.3p385 :010 > $cache.set 'test', target
 => nil 
1.9.3p385 :011 > $cache.get 'test'
 => {:first=>"Moin", :last=>"Haidar"}

Tuesday, February 12, 2013

Incompatible JavaHL library loaded. 1.7.x or later required


apt-add-repository ppa:dominik-stadler/subversion-1.7
apt-get update
apt-get dist-upgrade

Alt-Tab does not switch Ubuntu 12.04


Fin Compiz Confg Manager
sudo find / -name compizconfig-settings-manager

Not Found?

Install Compiz Config Settings Manager:
sudo apt-get install compizconfig-settings-manager

Then go to system tools > preferences > Compiz Config Manager
Select "Window Management Tab"
Check on "Application Switcher"

That's It.

Thursday, April 26, 2012

Rhomobile: rake aborted starting redis server


You might be getting following error while starting redis([bundle exec rake redis:start]) after bundle and rake dtach:install as per this documentation: http://docs.rhomobile.com/rhoconnect/tutorial

dtach -A /tmp/redis.dtach redis-server ./redis.conf
dtach: could not execute redis-server: No such file or directory

I needed to do [bundle exec] rake redis:install as well to make it working as I was missing redis.conf, redis-server etc.

You should see following when executing [bundle exec] rake redis:install

bash-3.2$ bundle exec rake redis:install

See http://redis.io/ for information about redis.

git clone git://github.com/antirez/redis.git /tmp/redis -n
Cloning into /tmp/redis...
remote: Counting objects: 16528, done.
remote: Compressing objects: 100% (5777/5777), done.
remote: Total 16528 (delta 12018), reused 14993 (delta 10590)
Receiving objects: 100% (16528/16528), 3.89 MiB | 246 KiB/s, done.
Resolving deltas: 100% (12018/12018), done.
cd /tmp/redis/ && git reset --hard && git checkout 2.4.1
HEAD is now at a3eb7ac Re-introduce -g -rdynamic -ggdb when linking, fixing strack traces.
Note: checking out '2.4.1'.

You are in 'detached HEAD' state. You can look around, make experimental
changes and commit them, and you can discard any commits you make in this
state without impacting any branches by performing another checkout.

If you want to create a new branch to retain commits you create, you may
do so (now or later) by using -b with the checkout command again. Example:

  git checkout -b new_branch_name

HEAD is now at ab648d9... 2.4.1 release notes.
cd /tmp/redis/ && make clean
cd src && make clean
rm -rf redis-server redis-benchmark redis-cli redis-check-dump redis-check-aof *.o *.gcda *.gcno *.gcov
cd deps/hiredis && make clean
rm -rf libhiredis.dylib libhiredis.a hiredis-example hiredis-test hiredis-example* *.o *.gcda *.gcno *.gcov
cd deps/linenoise && make clean
rm -f linenoise_example *.o
(cd deps/jemalloc && make distclean)
make[1]: *** No rule to make target `distclean'.  Stop.
make: [clean] Error 2 (ignored)
cd /tmp/redis/ && make
cd src && make all
MAKE hiredis
cc -c -std=c99 -pedantic -O3 -fPIC -Wall -W -Wstrict-prototypes -Wwrite-strings   -arch i386 -arch x86_64 -g -ggdb  net.c
cc -c -std=c99 -pedantic -O3 -fPIC -Wall -W -Wstrict-prototypes -Wwrite-strings   -arch i386 -arch x86_64 -g -ggdb  hiredis.c
cc -c -std=c99 -pedantic -O3 -fPIC -Wall -W -Wstrict-prototypes -Wwrite-strings   -arch i386 -arch x86_64 -g -ggdb  sds.c
cc -c -std=c99 -pedantic -O3 -fPIC -Wall -W -Wstrict-prototypes -Wwrite-strings   -arch i386 -arch x86_64 -g -ggdb  async.c
libtool -static -o libhiredis.a - net.o hiredis.o sds.o async.o
MAKE linenoise
cc  -c -Wall -W -Os -g linenoise.c
cc  -c -Wall -W -Os -g example.c
cc  -Wall -W -Os -g -o linenoise_example linenoise.o example.o

...
...
cp /tmp/redis/src/redis-benchmark /usr/local/bin
cp /tmp/redis/src/redis-cli /usr/local/bin
cp /tmp/redis/src/redis-server /usr/local/bin
Installed redis-benchmark, redis-cli and redis-server to /usr/local/bin
mkdir /usr/local/etc
cp /tmp/redis/redis.conf /usr/local/etc/redis.conf
Installed redis.conf to /usr/local/etc
 You should look at this file!