Sunday, December 25, 2011

You need to specify gem names as Strings. Use 'gem "test"' instead.

This can happen due to syntax error in your Gemfile. Fix the sytax error by manually checking this file. If that does not work delete the lines that you added to result in this problem and copy / paste from a working copy of a Gemfile.

Wednesday, December 07, 2011

Thursday, December 01, 2011

`test': unknown command 't' (ArgumentError)

To write tests using Test::Unit new syntax :

test "truth" do
  assert true
end

1. gem install test-unit
2. Code:

require 'rubygems'
gem 'test-unit'
require 'test/unit'


class ExampleTest < Test::Unit::TestCase
  def test_truth
    assert true
  end
 
  test "truth" do
    assert true
  end
end


3. Run: ruby example_test This will work on ruby-1.9.3-p0.

Reference:  Test::Unit and MiniTest with different Ruby versions

Wednesday, November 30, 2011

Installing Ruby 1.9.3 using RVM on Mac OS Lion

ERROR: The provided CC(gcc) is LLVM based, it is not yet fully supported by ruby and gems, please read `rvm requirements`.

1) Download Xcode 4.2.x via App Store.
2) Go to Applications folder and click Install Xcode
3) Download and install GCC from https://github.com/kennethreitz/osx-gcc-installer
4) In a new terminal run : export CC=gcc
and then run : rvm install 1.9.3
5) You may also want to upgrade ruby gems by running:
gem update --system

Wednesday, November 02, 2011

ActiveRecord::Relation, undefined method error

If you are using the active record relationships to access columns, for instance:

Article has many comments
article.comments.where("spam = ?", false).order("created_at asc")

This returns ActiveRelation object that does not fire the query. Only when you loop through the results you can access the columns of comments objects. If you want to force the call to the database just append "all" to it like this:

article.comments.where("spam = ?", false).order("created_at asc").all

Monday, October 24, 2011

(local out of date) error in Git when working with branches

1. git pull origin your-branch
2. git push origin your-branch

Step 1 brings your local branch to up-to date. Step 2 pushes your changes to the remote branch.

Sunday, October 23, 2011

invalid date format in specification: gem ruby

1) Upgraded ruby gems to 1.8.11 (gem update --system)
2) gem pristine --all

No luck.

Deleted all the gemspec that were causing problems: whenever-0.6.8.gemspec etc. Then bundle install made it work.

`build_extensions': ERROR: Failed to build gem native extension. (Gem::Installer::ExtensionBuildError)

I was getting :
Installing eventmachine (0.12.10) with native extensions .rvm/rubies/ruby-1.8.7-p330/lib/ruby/site_ruby/1.8/rubygems/installer.rb:533:in `build_extensions': ERROR: Failed to build gem native extension. (Gem::Installer::ExtensionBuildError)

during the installation of scheduler_daemon on Mac OS Lion. Upgraded XCode via appstore (download from appstore and install) to resolve this issue.

Friday, October 07, 2011

Integrating Tweet Button in Rails App

In Rails 3.0 app:

1) In Gemfile include:

gem 'tweet-button'

2) bundle install

3) In application_helper.rb include:

module ApplicationHelper
include TweetButton

... other methods...
end

4) In your partial:

<%= tweet_button(:via => "CreditCardLogic", :url => polymorphic_url(article), :text => "Check this out!") %>

To see this in action, check out my credit cards site.

Tuesday, September 27, 2011

Making a Branch the Master in GIT

git checkout cat_killer
git merge -s ours master
git checkout master
git merge cat_killer
git push

cat_killer is the branch you want to make the master.

Stolen from Stackoverflow post.

Tuesday, September 20, 2011

no mongrel gem found in sdk rubymine

Even if you are using RVM, Rubymine actually looks at the global installation for the gem. Install thin, mongrel etc on the global Ruby installation that is independent of any gemset.

How to start Thin server on a different port?

thin start -p 80

Friday, August 12, 2011

require that is compatible with ruby 1.8.x and 1.9.x

require File.expand_path(File.join(File.dirname(__FILE__), 'player'))

This makes : require 'player' work on both Ruby 1.8.x and 1.9.x

Sunday, August 07, 2011

ImageMagick Installer

Download the script from https://github.com/maddox/magick-installer/blob/master/magick-installer.sh and run it.

ImageScience on Snow Leopard

1) Download and install MacPorts http://www.macports.org/install.php
2) sudo port install freeimage
3) env ARCHFLAGS="-arch x86_64" gem install RubyInline image_science

Wednesday, July 27, 2011

Reserved Words in Rails

To find out if a given name is reserved in Rails programmatically, check out this How to find out if a name is reserved in Rails 4.2.5.

* ADDITIONAL_LOAD_PATHS
* ARGF
* ARGV
* ActionController
* ActionView
* ActiveRecord
* ArgumentError
* Array
* BasicSocket
* Benchmark
* Bignum
* Binding
* CGI
* CGIMethods
* CROSS_COMPILING
* Class
* ClassInheritableAttributes
* Comparable
* ConditionVariable
* Config
* Continuation
* DRb
* DRbIdConv
* DRbObject
* DRbUndumped
* Data
* Date
* DateTime
* Delegater
* Delegator
* Digest
* Dir
* ENV
* EOFError
* ERB
* Enumerable
* Errno
* Exception
* FALSE
* FalseClass
* Fcntl
* File
* FileList
* FileTask
* FileTest
* FileUtils
* Fixnum
* Float
* FloatDomainError
* GC
* Gem
* GetoptLong
* Hash
* IO
* IOError
* IPSocket
* IPsocket
* IndexError
* Inflector
* Integer
* Interrupt
* Kernel
* LN_SUPPORTED
* LoadError
* LocalJumpError
* Logger
* Marshal
* MatchData
* MatchingData
* Math
* Method
* Module
* Mutex
* Mysql
* MysqlError
* MysqlField
* MysqlRes
* NIL
* NameError
* NilClass
* NoMemoryError
* NoMethodError
* NoWrite
* NotImplementedError
* Numeric
* OPT_TABLE
* Object
* ObjectSpace
* Observable
* Observer
* PGError
* PGconn
* PGlarge
* PGresult
* PLATFORM
* PStore
* ParseDate
* Precision
* Proc
* Process
* Queue
* RAKEVERSION
* RELEASE_DATE
* RUBY
* RUBY_PLATFORM
* RUBY_RELEASE_DATE
* RUBY_VERSION
* Rack
* Rake
* RakeApp
* RakeFileUtils
* Range
* RangeError
* Rational
* Regexp
* RegexpError
* Request
* RuntimeError
* STDERR
* STDIN
* STDOUT
* ScanError
* ScriptError
* SecurityError
* Signal
* SignalException
* SimpleDelegater
* SimpleDelegator
* Singleton
* SizedQueue
* Socket
* SocketError
* StandardError
* String
* StringScanner
* Struct
* Symbol
* SyntaxError
* SystemCallError
* SystemExit
* SystemStackError
* TCPServer
* TCPSocket
* TCPserver
* TCPsocket
* TOPLEVEL_BINDING
* TRUE
* Task
* Text
* Thread
* ThreadError
* ThreadGroup
* Time
* Transaction
* TrueClass
* TypeError
* UDPSocket
* UDPsocket
* UNIXServer
* UNIXSocket
* UNIXserver
* UNIXsocket
* UnboundMethod
* Url
* VERSION
* Verbose
* YAML
* ZeroDivisionError

Other names that have been reported to cause trouble:

* accept
* callback – breaks validation if used as a model method.
* categorie
* action
* attributes – if you have a has_many called attributes, you can’t access to your object attributes anymore; only the associated objects
* application2
* @base_path – setting this variable name in a controller method seems to break the ablity to render a partial in the view. The view will render with no content and no errors will be generated .
* connection – there seems to be a connection class already
* database – (in mysql)
* dispatcher
* display1
* drive – fixtures will not autogenerate IDs in Rails 2.0.2
* errors
* format
* host – I had a text_field :host, :name that I saw problems with. (JR)
* key
* layout – If you have a model called Layout and in a controller have “scaffold :layout” it generates an exception. However, if you script/generate the scaffold for layout it works.
* load – When making an Ajax call to an action named load, the action’s code will be skipped (or otherwise rendered useless). This is made apparent by: a) @variables are not available in the view, b) calling render :layout => false still yields the layout.
* link – breaks migrations when used as a column name in combination with validation: ticket
* new, override to news if you want a news table
* notify – not a valid column name
* open – not a valid column name
* public
* quote ‘quote’ cannot be used as a column name
* render – cannot be used as an action name
* request
* records – a table named records seemed to cause duplicate entries to be found by find
* responses – scaffold borks with "undefined method ‘body=’ "
* save – ActiveRecord uses this to save the object.
* scope – do not use as an association name because ActiveRecord::Base.scope is called instead
* send
* session (session_controller or SessionController will not work)
* system – a table column named system causes problems when trying to generate scaffold
* template – a table named templates causes an error when you try to invoke the create method of the default controller
* test (however those work with ruby test/unit/axistest.rb_ and rake testunits_)
* timeout – an ActiveRecord attribute named timeout will clash with the global function “timeout” defined in Ruby’s timeout.rb
* to_s — naming a model instance method to_s resulted in ‘File not found’ for any view an object of this class (should have) appeared in (no matter which method called) and WebRick had to be restarted. I couldn’t drag the very cause into light, but in the traces ‘to_s’ gave me a hint. After renaming everything worked well again.
* type — or any of the other MagicFieldNames
* URI
* visits — a table column named visits causes problems when trying to query some_obj.visits.
* Observer — for a model name works in development environment but not in production.
singular names finishing in “s”: Axis → Axes, Access → Accesses, will break the pluralization in rake: Axi, Acces

Monitor cannot be used. It is a Ruby class that is related to threading.

List of Magic Field Names

* created_at
* created_on
* updated_at
* updated_on
* lock_version
* type
* id
* #{table_name}_count
* position
* parent_id
* lft
* rgt
* quote_value (is used for quoting)
* template

uninstalling rake 0.9.2

gem uninstall rake
ERROR: While executing gem ... (Gem::InstallError)
cannot uninstall, check `gem list -d rake`

1) gem list -d rake

gives:

*** LOCAL GEMS ***

rake (0.9.2, 0.8.7)
Author: Jim Weirich
Rubyforge: http://rubyforge.org/projects/rake
Homepage: http://rake.rubyforge.org
Installed at (0.9.2): /Users/bparanj/.rvm/gems/ruby-1.9.2-p180@global
(0.8.7): /Users/bparanj/.rvm/gems/ruby-1.9.2-p180@global

2) rvm use @global && gem uninstall rake -v 0.9.2

uninstalls rake

Friday, July 15, 2011

Installing Ruby Debug

1) From the root of the project run:
gem install ruby-debug19 -- --with-ruby-include="$rvm_path/src/$(rvm tools identifier)/"

2) Include in Gemfile

group :test, :development do
gem ‘ruby-debug19′, :require => ‘ruby-debug’
end

3) Create a .rdebugrc in your home directory

set autolist
set autoeval
set autoreload
set forcestep


4)
Specify how you would like Rails to report deprecation notices for your bugger environment, set
config.active_support.deprecation to :log, :notify or :stderr at config/environments/bugger.rb


5) require 'ruby-debug' in development.rb. Edit source where you want to debug to include :

debugger

6) Start server in debug mode:
rails s -d

References

http://pivotallabs.com/users/chad/blog/articles/366-ruby-debug-in-30-seconds-we-don-t-need-no-stinkin-gui-
http://bashdb.sourceforge.net/ruby-debug.html
http://railscasts.com/episodes/54-debugging-with-ruby-debug

Friday, July 08, 2011

Sunday, June 26, 2011

Reserved Words You Can’t Use in Rails

It would be nice if the Rails generator fails to generate when you use the reserved words for a model. I wasted lot of time when I used words like monitor as a model name and class, type as an attribute for a model.

Here is a list of words that cannot be used
.

Wednesday, June 22, 2011

List of types to use in script/generate model

he attributes are SQL types, hence the following are supported:

* :primary_key
* :string
* :text
* :integer
* :float
* :decimal
* :datetime
* :timestamp
* :time
* :date
* :binary
* :boolean

Stolen from stackoverflow

How to remove a ignore a file in git that is already in git?

git rm --cached

Reference: Git

Tuesday, May 31, 2011

Could not find nokogiri-1.4.4 in any of the sources on Ubuntu

If you get the error: "Could not find nokogiri-1.4.4 in any of the
sources" it is probably related to "libxm12" missing. In fact, that
library is probably there. What you are missing is the development
version:

sudo apt-get install libxml2-dev

nokogiri should then install.

Reference: Manual Install

Sunday, May 22, 2011

Forcing DNS changes to take effect on Snow Leopard

I made a mistake while setting up the DNS on Linode. In order to flush the old DNS server settings. I had to run:

dscacheutil -flushcache

Then create a new zone with the right IP Address. Just ping the hostname to find the IP Address and check if it is correct by comparing it to the Linode dashboard.

Wednesday, May 11, 2011

How to highlight tabs in Rails

1) Include the following method in application helper.

def is_active?(page_name)
# logger.info("lllllllllllll #{page_name}")
# logger.info("cccccccccccccc #{params[:controller]}")
"current" if params[:controller] == page_name
end

2) In your layout, add this:

<%= link_to 'Articles', new_article_path, :class => is_active?("articles") %>


3) Uncomment the logger lines to see which controller is handling the request and just fill in
the parameters for is_active? method

Fixed an error from the code I found from an original post in Stackoverflow.

Thursday, May 05, 2011

Installing Postgres on Snow Leopard

1) sudo port install postgresql83 postgresql83-server
2)

sudo mkdir -p /opt/local/var/db/postgresql83/defaultdb
sudo chown postgres:postgres /opt/local/var/db/postgresql83/defaultdb
sudo su postgres -c '/opt/local/lib/postgresql83/bin/initdb -D /opt/local/var/db/postgresql83/defaultdb'

3) sudo launchctl load -w /Library/LaunchDaemons/org.macports.postgresql83-server.plist

4) sudo su postgres -c '/opt/local/lib/postgresql83/bin/postgres -D /opt/local/var/db/postgresql83/defaultdb'

5) sudo vi /etc/profile

6) Add : PATH="/opt/local/bin:/opt/local/sbin:/opt/local/lib/postgresql83/bin:$PATH"

7) createuser --superuser your_macusername -U postgres

8) createdb my_database

9) sudo env ARCHFLAGS="-arch x86_64" gem install pg

10) database.yml
development:
adapter: postgresql
database: your_db
username: your_db_username

Installing pgAdmin

sudo port install pgAdmin3

Upon completion of installation, you can find the application in /Applications/MacPorts/pgAdmin3


Reference:
Installing PostgreSQL on Snow Leopard 10.6


Installing PostgreSQL on Leopard using MacPorts

Saturday, April 30, 2011

No such file or directory - /tmp/mysql.sock

Fix : sudo ln -s /var/run/mysqld/mysqld.sock /tmp/mysql.sock

Reference : No such file or directory

How to customize Flash messages in Devise Rails gem

Customize the config/locales/devise.en.yml file in your project.

undefined local variable or method `confirmed_at' for

Devise Rails plugin throws this error when you don't have the

t.confirmable

in the users migration.

/etc/hosts file messed up on Snow Leopard

Whenever I run a Rails app, I had to access it via http://0.0.0:port_number. Devise Rails plugin sample app barks when redirecting with this error message:

ERROR URI::InvalidURIError: the scheme http does not accept registry part: 0.0.0:3000 (or bad hostname?)


1) To cleanup the mess, I edited the /etc/hosts file so it now looks like this:

##
# Host Database
#
# localhost is used to configure the loopback interface
# when the system is booting. Do not change this entry.
##
127.0.0.1 localhost
255.255.255.255 broadcasthost
::1 localhost
fe80::1%lo0 localhost

2) Then flush the cache to pickup the new changes by running :

sudo dscacheutil -flushcache

Now you can access your local Rails apps by : http://localhost:port_number and Devise is happy again.

Thursday, April 28, 2011

sudo: no tty present and no askpass program specified

When trying to deploy to a new staging server, I get the following
error:

sudo: no tty present and no askpass program specified

Solution:

Add the line: default_run_options[:pty] = true
in your deploy.rb

Tuesday, April 19, 2011

how to get all the branches that is remote in git

If you have many remote branches that you want to fetch at once:

$ git remote update
$ git pull --all

Now you can checkout any branch as you need to, without hitting the remote repo.


http://stackoverflow.com/questions/67699/how-do-i-clone-all-remote-branches-with-git

Sunday, April 17, 2011

Source code formatter for Blogspot

Very useful source code formatter for blogspot

Ruby Programming Language Book Notes 2

| operator is used for union operation in Array.
& operator is used for intersection operation in Array.


1: class Array
2: def union(another)
3: self | another
4: end
5: def intersection(another)
6: self & another
7: end
8: end

Saturday, April 16, 2011

Ruby Programming Language Book Notes

1)

minimum = if x < y then x else y end

can also be written as :

minimum = x < y ? x : y

2)

class Fixnum
def inclusive(element)
self..element
end

def exclusive(element)
self...element
end
end

This eliminates the mental mapping from .. and ... to the behaviour of the methods.

3) This does not work:

class Fixnum
alias inclusive ..
alias exclusive ...
end

gives syntax error, unexpected tDOT2

So how do you redefine the .. and ...? If you do ri Fixnum, it shows the instance methods. The section on Operators has discussion on operators that can be re-defined.

Thursday, April 14, 2011

Convert Haml to ERB

1) script/plugin install http://github.com/cgoddard/haml2erb.git

2) In console:
hamls = Dir["app/views/**/*.haml"] - ['app/views/layouts/screen.html.haml'];
hamls.each do |haml|
puts haml
erb = haml.sub(/\.haml$/, '.erb')
File.open(erb, 'w') do |file|
file.write Haml2Erb.convert(File.read(haml))
end
end

http://makandra.com/notes/544-convert-haml-to-erb

ERROR: There has been an error fetching the ruby interpreter. Halting the installation.

This happens when there is no network connection. How wonderful it would be if developers can give error messages that make sense! Make the code robust and give users a clear call to action to rectify any errors that they can recover from. It is surprising that even ruby gems has the same issue.

Sunday, April 03, 2011

Mispelled HTTP_REFERER in Rails 3.0

The correct spelling is HTTP_REFERRER but Rails source has it with wrong spelling. So in order to get the HTTP_REFERRER do the following in your controller:

request.env["HTTP_REFERER"]

request.domain has been deprecated. The domain method has been moved to ActionDispatch::Http::URL. Ideally we want to use the method defined in this module.Do to metaprogramming it is difficult to figure out the actual keys that are used in ActionDispatch::Request. If you run this snippet:

request.env.keys.each do |x|
logger.info x
end

You will get all the keys:

action_dispatch.request.formats
action_dispatch.request.parameters
rack.session
HTTP_ACCEPT
HTTP_HOST
SERVER_NAME
rack.request.cookie_hash
action_dispatch.remote_ip
rack.url_scheme
HTTP_KEEP_ALIVE
HTTP_USER_AGENT
REQUEST_PATH
action_dispatch.request.query_parameters
action_dispatch.request.unsigned_session_cookie
SERVER_PROTOCOL
HTTP_ACCEPT_LANGUAGE
rack.errors
action_dispatch.secret_token
async.callback
REMOTE_ADDR
PATH_INFO
rack.run_once
rack.version
SERVER_SOFTWARE
action_dispatch.request.path_parameters
rack.request.cookie_string
SCRIPT_NAME
HTTP_REFERER
action_dispatch.parameter_filter
HTTP_COOKIE
HTTP_VERSION
rack.multithread
action_dispatch.request.request_parameters
action_dispatch.cookies
REQUEST_URI
rack.multiprocess
rack.request.query_hash
SERVER_PORT
HTTP_ACCEPT_CHARSET
action_controller.instance
rack.session.options
async.close
REQUEST_METHOD
warden
rack.request.query_string
action_dispatch.request.content_type
GATEWAY_INTERFACE
HTTP_CONNECTION
HTTP_ACCEPT_ENCODING
QUERY_STRING
rack.input

Now you can access any of these environment values from your controller similar to the referrer.

Saturday, April 02, 2011

Accessing Webrick running on VM from Mac OS

1) If the VM is running, stop it.

2) To forward from port 3001 on the host to port 3000 on the guest, run the following command on the host.
$ VBoxManage modifyvm "Ubuntu" --natpf1 "webrick,tcp,,3001,,3000"

3) To delete the port forwarding run:

VBoxManage modifyvm "Ubuntu" --natpf1 delete "webrick"

4) Now you can go to http://localhost:3001 on your host to hit webrick running on your VM.

The page loads very slow. Is there any way to speed it up?

Sunday, March 13, 2011

My Job Went to India Book Review

Businesses cannot exist without the IT and vice-versa. They are interdependent. IT systems automate the business processes and run 24 by 7. Therefore we cannot really view those who work at the “Business” level as above us. So, I disagree with the author on this point. However, he does sort of make a U turn later on in the book.

This book will make you think. For instance: What is the supply demand for programmers in a particular Business domain? This would be a good question to research so that we can plan our career.

He talks about how to survive layoffs by being knowledgeable in different areas. Not everyone wants to stay in one organization for a long time. Another thing is that it is almost impractical to learn everything in a particular technology (say, Java technology). Developers will have different intentions, for example they might have a backup plan in case of IT downturn, either by having a cash cushion or generating cash flow through software products.

I agree about following your passion. It enables us to transcend limitations. It inspires us and makes us reach a level of performance that amazes us. This explains the previous paragraph (which sounds like excuses).

Another principle that he explains - “Be the Worst” is very real. Two projects, one early in my career where I had the opportunity to work with a strong and talented team of developers and project manager. Recently when I found working for people who were not anywhere near my capabilities, they did affect my performance.

This book helps to see and expect what the work environment could possibly bring us and what we can do to proactively handle these situations.

Maintenance is seen as a menial work and recruiters downplay any experience on it. Oh, this is a developer job… Chad advises you to learn to love maintenance.

He recommends having a mentor and I am glad I read his book. I know mentors can also come in the form of a book!!! You can have more than one mentor.

I love the Eight-Hour Burn concept. This explains why I get very depressed and productivity drops during the last few weeks of the project. Now I know how to make the work stay in the office. No more nagging problems following me home!

The concept of “Presence” is very realistic. I learned this by making mistakes in the workplace and the cost was high. I wish I had read this book early in my career. Lot of things that he explains has already happened to me in my career. Still I was able to learn how to handle those situations successfully next time around.

Reading open source code really helps to solve recurring problems quickly. I have experienced this in my job. The cover of this book really needs to be improved. The content of the book is much better than the quality of cover image.

Thursday, March 03, 2011

Monday, February 28, 2011

Whole word search in Textmate

1) Command + Shift + f
2) Type in find :
\bsomething\b

Where something is the string you want to search

3) Check Regular expression box

Sunday, February 27, 2011

Getting Rails 3 running on Windows

Checkout the following resources for help:

http://accidentaltechnologist.com/ruby-on-rails/running-rails-3-on-windows/
http://accidentaltechnologist.com/ruby-on-rails/railsinstaller-is-instant-rails-evolved/
http://accidentaltechnologist.com/?s=rails
http://rubyinstaller.org/
http://sqlite.org/download.html (Go to precompiled binaries for Windows, download slitedll-3_7_3.zip , unzip it, copy the sqlite3. dll to Ruby bin directory, for example
c:\Ruby192\bin)

If you still need help, I recommend "Meet Rails 3 Part I" screencast by Peepcode.

Monday, January 17, 2011

Upgrading git on snow leopard

If you have followed

1. curl -O http://kernel.org/pub/software/scm/git/git-1.7.3.tar.bz2
2. tar xzvf git-1.6.4.2.tar.bz2
3. cd git-1.6.4.2
4. ./configure --prefix=/usr/local
5. make
6. sudo make install

Error installing ruby-1.8.7-p330 on Snow Leopard

The error :

make[1]: *** [readline.o] Error 1
make: *** [all] Error 1

Error running 'make ', please read ...make.log

Snow Leopard version is 10.6.5

1) Make sure you have the latest XCode installed. I have 3.2.5
2) rvm update && rvm reload
3) rvm_archflags="-arch x86_64"
4) rvm install ruby-1.8.7

Fixes the problem and installs ruby-1.8.7-p330.