Tuesday, March 13, 2012

Using Stubs with Test Spy in Ruby

While I was working on my super stealth product of my company - Affiliate Tracking system, I came across a problem during testing. I had to test the cookie setting logic of my controllers. It was straightforward to test that the cookie was set for the happy path. For the alternative scenario it became tricky to test because RSpec and Rails framework did not play that well together. I even read Devise Rails plugin code to see how Jose Valim handled cookie related problems during testing. No luck. One solution I found was on Stackoverflow. How do I test cookie expiry?


# app/controllers/widget_controller.rb
...
def index
    cookies[:expiring_cookie] = { :value   => 'All that we see or seem...', 
                                  :expires => 1.hour.from_now }
end
...
# spec/controllers/widget_controller_spec.rb
...
it "sets the cookie" do
  get :index
  response.cookies['expiring_cookie'].should eq('All that we see or seem...')
                                               # is but a dream within a dream.
                                               #                - Edgar Allan Poe
end

it "sets the cookie expiration" do
  stub_cookie_jar = HashWithIndifferentAccess.new
  controller.stub(:cookies) { stub_cookie_jar }

  get :index
  expiring_cookie = stub_cookie_jar['expiring_cookie']
  expiring_cookie[:expires].to_i.should be_within(1).of(1.hour.from_now.to_i)
end

This technique is a great example of Test Spy described in Gerard Mezos book xUnit Test Patterns. Basically, you install a spy and check the results collected by the test spy in the verification phase. In this case the Hash is the Test Spy that collects data. See how the stub is used to install the spy in the SUT? It overcomes the problems and isolates the SUT from the Rails framework and allows the code to be tested easily.

In my TDD bootcamps, the topic on Stubs and Mocks generates lot of discussion. To clear confusion that surrounds the stubs and mocks, I would state : Read Martin Fowler's paper on Mocks Aren't Stubs, Stub can never fail your test, only mocks can fail your test. Using stubs in combination with a spy like this makes stubs seem like they can in fact fail your test. But only the data collected by the Test Spy decides whether the test passes or not. So the stub's main purpose is to just isolate the production code from Rails framework and allow access to the internal state of the SUT where there is no direct way to access it.

Saturday, March 10, 2012

Tuesday, February 07, 2012

Testing and Command Query Separation Principle

The term 'command query separation' was coined by Bertrand Meyer in his book "Object Oriented Software Construction".

The fundamental idea is that we should divide an object's methods into two categories:

    Queries: Return a result and do not change the observable state of the system (are free of side effects).
    Commands: Change the state of a system but do not return a value.

Because the term 'command' is widely used in other contexts it is referred as 'modifiers' and 'mutators'.

It's useful if you can clearly separate methods that change state from those that don't. This is because you can use queries in many situations with much more confidence, changing their order. You have to be careful with modifiers.

The return type is the give-away for the difference. It's a good convention because most of the time it works well. Consider iterating through a collection in Java: the next method both gives the next item in the collection and advances the iterator. It's preferable to separate advance and current methods.

 There are exceptions. Popping a stack is a good example of a modifier that modifies state. Meyer correctly says that you can avoid having this method, but it is a useful idiom. Follow this principle when you can.

From jMock home page: Tests are kept flexible when we follow this rule of thumb: Stub queries and expect commands, where a query is a method with no side effects that does nothing but query the state of an object and a command is a method with side effects that may, or may not, return a result. Of course, this rule does not hold all the time, but it's a useful starting point.

Saturday, February 04, 2012

Stubs are not Mocks - Concise Version of Martin Fowler's Article

Stubs - a common helper to testing environments. There is a difference in how test results are verified: a distinction between state verification and behavior verification. Focusing on one element of the software at a time -hence the common term unit testing. The problem is that to make a single unit work, you often need other units.
  • Dummy objects are passed around but never actually used. Usually they are just used to fill parameter lists.
  • Fake objects actually have working implementations, but usually take some shortcut which makes them not suitable for production (an in memory database is a good example).
  • Stubs provide canned answers to calls made during the test, usually not responding at all to anything outside what's programmed in for the test. Stubs may also record information about calls, such as an email gateway stub that remembers the messages it 'sent', or maybe only how many messages it 'sent'.
  • Mocks are what we are talking about here: objects pre-programmed with expectations which form a specification of the calls they are expected to receive.
Only mocks insist upon behavior verification. The other doubles can, and usually do, use state verification.

The classical TDD style is to use real objects if possible and a double if it's awkward to use the real thing. A mockist TDD practitioner, however, will always use a mock for any object with interesting behavior.
An acknowledged issue with state-based verification is that it can lead to creating query methods only to support verification. It's never comfortable to add methods to the API of an object purely for testing, using behavior verification avoids that problem.

Thursday, January 26, 2012

RCov Tips

1. How to turn off rcov for specific sections in a file:
Start and end with :

#:nocov:

in your file.

2. How to exclude files from rcov:

In spec directory, edit rcov.opts

 append our path of files to –exclude option. Eg: –exclude “helpers/*,app/sweepers/*”.

Reference

http://psixty.wordpress.com/2010/06/22/how-to-exclude-files-in-rcova-code-coverage-tool-in-ruby/

Monday, January 16, 2012

How to uninstall all gems in global rvm ?

rvm use @global 
rvm gemset empty global

If you want to remove all gems for a particular gemset, replace global with your-gemset-name

gem "rake" is not installed

Problem uninstalling rake? Run the following command:
rvm use @global && gem uninstall rake

Thursday, January 12, 2012

How to disable acts_as_audited 2.0 rails plugin in Rails 3.1 and RSpec

Create disable.rb under spec/support folder and call disable_auditing method on your modes. For example:
Account.disable_auditing
Cart.disable_auditing

Monday, January 09, 2012

Using Reek gem in Rails 3.1 projects

1. gem install reek
2. reek lib/*.rb > myreport.txt

You can run reports for app/models/*.rb, app/controllers/*.rb and app/helpers/*.rb

rcov for Rails 3.1

1. rake spec:rcov
2. open coverage/index.html
3. add coverage/* to your .gitignore file.
4. $ rake -T rcov
rake spec:clobber_rcov  # Remove rcov products for rcov
rake spec:rcov          # Run all specs in spec directory with RCov (excluding plugin specs)

Rails Best Practices

1. gem install rails_best_practices
2. gem install ripper
3. From the root of the project run: 
rails_best_practices -f html .
to generate the report.

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

Wednesday, June 15, 2011

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.

Monday, November 15, 2010

Rack Developers Notebook

Download the book from : http://www.meetup.com/silicon-valley-ruby/files/

Sunday, September 12, 2010

How to install MongoDB on OS X

Download, unpack, and install the pre-compiled 64-bit binaries:




curl -O http://downloads.mongodb.org/osx/mongodb-osx-x86_64-1.6.2.tgz
tar xzf mongodb-osx-x86_64-1.6.2.tgz
sudo mv mongodb-osx-x86_64-1.6.2 /opt/local/mongodb
sudo mkdir /opt/local/mongodb_data /var/log/mongodb
sudo chown -R root /opt/local/mongodb


(If you’re on a 32-bit machine, substitute in i386 for each x86_64 above.)




Next, you’ll want to make a config file so you can change the server’s options without fiddling with command-line arguments.




Save as: /opt/local/mongodb/mongod.conf




# Store data alongside MongoDB instead of the default, /data/db/
dbpath = /opt/local/mongodb_data

# Only accept local connections
bind_ip = 127.0.0.1


Now, we’ll make a launchd job to register the server as an OS X daemon. launchd will start the server at startup, stop it before shutdown, make sure it stays up, and redirect its output to a nice log file.




Save as: /Library/LaunchDaemons/org.mongodb.mongod.plist




<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN"
"http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
<key>Label</key>

<string>org.mongodb.mongod</string>
<key>ProgramArguments</key>
<array>
<string>/opt/local/mongodb/bin/mongod</string>

<string>run</string>
<string>--config</string>
<string>/opt/local/mongodb/mongod.conf</string>
</array>

<key>RunAtLoad</key>
<true/>
<key>KeepAlive</key>
<true/>
<key>WorkingDirectory</key>

<string>/opt/local/mongodb</string>
<key>StandardErrorPath</key>
<string>/var/log/mongodb/output.log</string>
<key>StandardOutPath</key>

<string>/var/log/mongodb/output.log</string>
</dict>
</plist>


Now we just need to load the launchd job:




sudo launchctl load /Library/LaunchDaemons/org.mongodb.mongod.plist


And that should do it! Try visiting http://localhost:28017 to see the status console for your database.




One last thing: you should probably add /opt/local/mongodb/bin to your $PATH. That way you can use the other binaries that ship with MongoDB, like the mongo console, mongoexport, and so on.




You can adjust your path the regular way by editing your shell’s profile, or you can use this nice paths.d mechanism that OS X provides:




sudo sh -c 'echo "/opt/local/mongodb/bin" > /etc/paths.d/mongodb'

Saturday, September 11, 2010

Install Postgresql server on Ubuntu 10.04

1) sudo apt-get install postgresql
2) sudo apt-get install postgresql-client
3) sudo /etc/init.d/postgresql-8.4 restart
4) ALTER USER postgres with encrypted password 'your_password';
5) sudo /etc/init.d/postgresql-8.4 restart

Install Java 6 on Ubuntu 10.04

1) sudo add-apt-repository "deb http://archive.canonical.com/ lucid partner"
2) sudo apt-get update
3) sudo aptitude install curl sun-java6-bin sun-java6-jre sun-java6-jdk

Reference:

Install Java 6 on Ubuntu

Friday, September 10, 2010

Cloning a VM with mutiple snapshots

As of 3.0.8 (or before) the VBoxManage clonehd command can clone any snapshot of a hard disk or clone the Current State of a hard disk. The resulting VDI file is flattened (it does not have any other snapshots attached).
You need to find the UUID of the Current State image file, or of the Snapshot image file (NOT the UUID of the snapshot!)
To clonehd the Current State of a disk:

* Open the Virtual Media Manager (Menu: File>Virtual Media Manager).
* Navigate to the hard disk you want to clone and fully expand the tree (use * key on numeric keypad).
* Find the {hexUUID}.vdi file that is attached to the VM you want to clone the Current State of.
It will be (one of) the leaf files at the end of a branch.
When you select it, the 'Attached to:' text at the bottom of the window will say:
'Attached to: ', without any (snaphot name) in brackets after it.
* Click the filename to the right of the 'Location:' displayed at the bottom of the window.
* Ctrl+C / Copy to copy the text to the clipboard, which will be something like:
(path){b6441469-5ccb-418c-8fdd-73c5e1a17314}.vdi
* Ctrl+V / Paste and extract the hexUUID value (removing the {} brackets) and run clonehd to clone it!
CODE: C:> VBoxManage clonehd b6441469-5ccb-418c-8fdd-73c5e1a17314 CloneDisk.vdi

To clonehd a snapshot of a disk:

* Find the {hexUUID}.vdi file that is attached to the VM (and Snapshot) you want to clone.
* It will be one of the files along a branch.
When you select it, the 'Attached to:' text at the bottom of the window will say:
'Attached to: ()', with (snaphot name) in brackets after it.
* Follow the instructions above for cloning the current state of a disk.



Reference:

This thread

Wednesday, September 08, 2010

VirtualBox Shared Folders between Ubuntu 10.04 Guest and Mac Host

You’ll need the VirtualBox (1.6 or above) with Guest Additions installed in Ubuntu.

* With the Virtual Machine powered off and selected in VirtualBox, go to:
Machine > Settings > Shared Folders
* For “Folder Path”, click the icon to browse for the folder you want to share.
* For “Folder Name”, enter a name to describe the share. Let's say vshare
* Click “OK” and start the virtual machine again.
* Create a mount point which is basically an empty folder. Example: /vmnt on the Ubuntu guest VM.
* Fire up the terminal and type:
sudo mount -t vboxsf folder_name path_to_mount_pointfolder_name is the name you typed in earlier to describe the share. Example: sudo mount -t vboxsf vshare /vmnt
* You should be able to browse the shared folder now.

Reference:

VirtualBox Shared Folders on Ubuntu

How to install KDevelop on Ubuntu 10.4

KDevelop is a decent editor for Rails projects. It gives a nice class browser view of your Rails project.

To resolve the error:
E: Package kdevelop has no installation candidate

before install, Go to :

1. Applications -> System Tools -> KPackage Edit
2. Settings -> Edit Software Sources -> Updates tab
3. Check "Unsupported Updates"
4. sudo apt-get update
5. Run : sudo apt-get install kdevelop

Alternate way:

1. sudo add-apt-repository ppa:kubuntu-ppa/backports
2. sudo apt-get update
3. sudo apt-get install kdevelop

To run KDevelop, just type kdevelop on the terminal

Tuesday, September 07, 2010

How to Install Guest Additions on CentOS 5.5

Prerequisite:

yum install yum-priorities
Make sure that yum-priorities is enabled by editing the /etc/yum/pluginconf.d/priorities.conf file, and ensuring that it contains the following lines:

[main]
enabled=1

Edit the .repo files in /etc/yum.repos.d/ and set up priorities by adding the line:

priority=N

to a repository entry, where N is an integer number from 1 to 99.
The recommended settings are:
[base], [addons], [updates], [extras] ... priority=1
[centosplus],[contrib] ... priority=2
Third Party Repos such as rpmforge ... priority=N (where N is > 10 and based on your preference)


Based on architecture: uname -i download the corresponding rpm into your downloads directory.

wget http://packages.sw.be/rpmforge-release/rpmforge-release-0.5.1-1.el5.rf.i386.rpm

rpm --import http://apt.sw.be/RPM-GPG-KEY.dag.txt rpm -K rpmforge-release-0.5.1-1.el5.rf.*.rpm

rpm -i rpmforge-release-0.5.1-1.el5.rf.*.rpm

yum check-update

Now you will be able to install dkms (You need sudo access to run these commands)


1) Devices > Install Guest Additions
2) Browse to the Guest Additions CD on the desktop, right click and open terminal. Run
sudo chmod +x VBoxLinuxAdditions-x86.run
3)yum install dkms
4) sudo yum install kernel-devel kernel-headers
sudo sh ./VBoxLinuxAdditions-x86.run

This will automatically switch VM to Seamless Mode and the resolution upgraded to 1024x768. You can now copy/paste from host to guest and vice-versa.

References:



How to Install Virtual Box Guest Additions for a Linux Guest


RPMForge

Saturday, August 28, 2010

Getting Rails and Sinatra to Share Sessions - Part I

Introduction

This is the first part of a series of blog posts that will show you how to setup your machine so that you can share sessions between Rails and Sinatra apps.

This idea was inspired by the In a World of Middleware, Who Needs Monolithic Applications? Mountain West Ruby Conference 2009 talk given by Corey Donohoe of Engine Yard.

However I will not be using Hancock or Hancock Client for Single Sign On. I think it is too complicated. I want something simple. My motivation is to build Rack compliant apps that are very focused on doing one thing really well and combining them to create a mashup.

At the end of the talk Corey said that in a world of why do we even need Rails? My opinion is that Rails app must be the last app in your Rack Stack and must be focused on your Core Domain. Anything else must be built as a Rack app. Because it is independent of your business and can be re-used across all your web apps.

Installation and Configuration

Environment: Ruby 1.8.7 managed by RVM

1)
gem install passenger

2)
passenger-install-apache2-module

Note: Steps 1 and 2 does not use sudo

3)
sudo mkdir /usr/local/apache2/conf

Add the lines shown during installation to httpd.conf file and save it in the directory created above.

In my case it is:

LoadModule passenger_module /Users/bparanj/.rvm/gems/ruby-1.8.7-p299/gems/passenger-2.2.15/ext/apache2/mod_passenger.so
PassengerRoot /Users/bparanj/.rvm/gems/ruby-1.8.7-p299/gems/passenger-2.2.15
PassengerRuby /Users/bparanj/.rvm/rubies/ruby-1.8.7-p299/bin/ruby

4) Setup folder to hold vhosts

sudo mkdir /usr/local/apache2/conf/vhosts

5) Add the following to the httpd.conf

NameVirtualHost *
Include /usr/local/apache2/conf/vhosts/*

6) Add virtual hosts to a file virtual_hosts.conf under /usr/local/apache2/conf/vhosts directory

# Example App

ServerName app.test
DocumentRoot /Users/benr/Rails/app/public
RailsEnv development



# Example App 2

ServerName app2.test
DocumentRoot /Users/benr/Rails/app2/public
RailsEnv development


7) Edit /etc/hosts file

sudo vi /etc/hosts

and add:

127.0.0.1 app.test app2.test

8)
sudo apachectl graceful or

sudo apachectl start

9) To restart app, create a file under RAILS_ROOT/tmp/restart.txt

when you run touch on restart.txt your Rails app will be reloaded

References:

http://benr75.com/2008/04/12/setup-mod_rails-phusion-mac-os-x-leopard
http://www.modrails.com/videos/passenger.mov

Sunday, August 15, 2010

error: Error running 'make ', please check. rvm/log/ruby-1.8.7-p299/make*.log

Step 1: Install readline.

1 curl -O ftp://ftp.cwru.edu/pub/bash/readline-6.0.tar.gz
2 tar -xvzf readline-6.0.tar.gz
3 cd readline-6.0
4 ./configure
5 make
6 sudo make install

Step 2: Install Ruby 1.8.7
rvm install 1.8.7 -C --enable-shared,--with-readline-dir=/usr/local

Wednesday, July 28, 2010

RSpec API - The Good and the Bad

The Good:

Operator Expressions : Good use of meta-programming

The Bad:

#1. Have method has bubble words and it complicates the API. It increases the noise in the code. Make the API minimal. (Bubble word - Words that does not do anything, but is used only for readability)

#2. Leaky API : render method is leaky because it depends on the argument passed in to the outer method. Basically it has parametric coupling. Developer has to *remember* the coupling in order to use the API.

Tuesday, July 27, 2010

undefined method `visit' for cucumber

Fix: Include the following configuration in features/support/env.rb

require 'webrat'
require 'webrat/core/matchers'

Webrat.configure do |config|
config.mode = :rack
config.open_error_files = false # Set to true if you want error pages to pop up in the browser
end

World(Webrat::Methods)
World(Webrat::Matchers)

This also fixes the error : "no such file to load -- action_controller/integration"

Saturday, July 24, 2010

Getting RSpec Book Rails app working on Rails 3.0 Beta 4

1. Create a new Rails app called blog, skip test unit since we will be using RSpec
rails new blog --skip-testunit

2. Edit gem file :

group :test do
gem 'rspec-rails', '>= 2.0.0.beta.10'
gem 'webrat'
gem 'selenium-client'
gem 'database_cleaner'
gem 'rspec-rails'
gem 'cucumber'
gem 'cucumber-rails'
gem 'rspec'
end

3. From app's root directory, run:

bundle install

4. rails g rspec:install

5. rails g cucumber:install

6. rails g cucumber:skeleton --rspec --webrat

7. rails g cucumber:feature

8. script/cucumber --tag @focus

9. script/cucumber -t @focus

10. rails g model movie showtime_date:date showtime_time:time
11. rake db:migrate
12. rake db:test:prepare
13. cucumber -t @focus
14. cucumber

Reference:

Rails 3, RSpec, and Cucumber

Monday, July 19, 2010

How to add a source to Ruby gems

gem sources -a http://gems.github.com

To remove a source:

gem sources -r http://gems.github.com

Run:
gem env

to see the sources that is currently in your Ruby gems.

Monday, July 12, 2010

Extremely Simple Alternative to AutoTest

I am reading the Rails 3 in Action by Yehuda. To run the sample code I customized the stakeout.rb to output the results of the test when specs get run whenever the file is changed.

1. Copy the source to a directory that is in your path:

#!/usr/bin/env ruby
if ARGV.size < 2
puts "Usage: stakeout.rb [files to watch]+"
exit 1
end

command = ARGV.shift
files = {}

ARGV.each do |arg|
Dir[arg].each { |file|
files[file] = File.mtime(file)
}
end

loop do

sleep 1

changed_file, last_changed = files.find { |file, last_changed|
File.mtime(file) > last_changed
}

if changed_file
files[changed_file] = File.mtime(changed_file)
puts "=> #{changed_file} changed, running #{command}"
puts system(command)
puts "=> done"
end

end

2. chmod +x stakeout.rb

3. To run:

stakeout.rb "spec bacon_spec.rb" **/*

This will run the spec called back_spec.rb whenever any files found recursively from the current file is changed.

Reference:

Faster TDD with Stakeout.rb

Problem Installing Sqlite3-ruby on Snow Leopard

I was getting this error when I started the server. I had installed RVM, Ruby 1.9.1, Rails 3.0 Beta 4:

.rvm/gems/ruby-1.9.1-p378/gems/sqlite3-ruby-1.3.1/lib/sqlite3/sqlite3_native.bundle: dlopen(.rvm/gems/ruby-1.9.1-p378/gems/sqlite3-ruby-1.3.1/lib/sqlite3/sqlite3_native.bundle, 9): no suitable image found. Did find: (LoadError)
.rvm/gems/ruby-1.9.1-p378/gems/sqlite3-ruby-1.3.1/lib/sqlite3/sqlite3_native.bundle: mach-o, but wrong architecture - .rvm/gems/ruby-1.9.1-p378/gems/sqlite3-ruby-1.3.1
/lib/sqlite3/sqlite3_native.bundle


Resolution:

Uninstall sqlite3-ruby (1.3.1)
1. gem uninstall sqlite3-ruby

Install sqlite3-ruby version 1.2.5
2. gem install sqlite3-ruby --version 1.2.5

If you get the error:

no such file to load -- sqlite3

when running rake db:migrate

Edit the Gemfile for the line sqlite3-ruby as :

gem 'sqlite3-ruby', :require => 'sqlite3'

Installing Ruby 1.9.2 using RVM on Snow Leopard

When I tried to install Ruby 1.9.2
rvm install 1.9.2

I got :

error: Error running 'make ', please check /Users/bparanj/.rvm/log/ruby-1.9.2-rc2/make*.log
error: There has been an error while running make. Aborting the installation.

Steps to Resolve :

1. Install libxml

curl -O ftp://xmlsoft.org/libxml2/libxml2-2.7.7.tar.gz
tar zxvf libxml2-2.7.7.tar.gz
cd libxml2-2.7.7
./configure --with-python=/System/Library/Frameworks/Python.framework/Versions/2.3/
make &
sudo make install

2. Install libxslt

curl -O ftp://xmlsoft.org/libxslt/libxslt-1.1.26.tar.gz
tar xvzf libxslt-1.1.26.tar.gz
cd libxslt-1.1.26
./configure
make
sudo make install

3.
rvm install 1.9.2-head -C --enable-shared,--with-readline-dir=/opt/local,--build=x86_64-apple-darwin10

Reference:

Installing Ruby 1.9.2 with RVM on Snow Leopard

Tips:

#1 :
rvm 1.9.2-head --default

to make it 1.9.2 when you open new terminal or after reboot.

#2 :
To revert to system installed Ruby:

rvm system --default

Thursday, July 08, 2010

uninitialized constant Mysql while running rake db:create

1. Uninstall the mysql gem

bparanj$ sudo gem uninstall mysql

Successfully uninstalled mysql-2.8.1

2. Installing the gem the right way on Snow Leopard
bparanj$ sudo env ARCHFLAGS="-arch i386" gem install mysql -- --with-mysql-config=/usr/local/mysql/bin/mysql_config
Building native extensions. This could take a while...
Successfully installed mysql-2.8.1
1 gem installed

3. Edit the gemfile and include the line:

gem 'mysql'

4. Run bundle install from the rails project directory:

mbp2:blog bparanj$ bundle install
Fetching source index from http://rubygems.org/
Using rake (0.8.7) from system gems
Using abstract (1.0.0) from system gems
Using activesupport (3.0.0.beta4) from system gems
Using builder (2.1.2) from system gems
Using i18n (0.4.1) from system gems
Using activemodel (3.0.0.beta4) from system gems
Using erubis (2.6.6) from bundler gems
Using rack (1.1.0) from bundler gems
Using rack-mount (0.6.6) from system gems
Using rack-test (0.5.4) from system gems
Using tzinfo (0.3.22) from system gems
Using actionpack (3.0.0.beta4) from system gems
Using mime-types (1.16) from system gems
Using polyglot (0.3.1) from system gems
Using treetop (1.4.8) from system gems
Using mail (2.2.5) from system gems
Using actionmailer (3.0.0.beta4) from system gems
Using arel (0.4.0) from system gems
Using activerecord (3.0.0.beta4) from system gems
Using activeresource (3.0.0.beta4) from system gems
Using bundler (0.9.26) from system gems
Using mysql (2.8.1) from system gems
Using thor (0.13.7) from bundler gems
Using railties (3.0.0.beta4) from system gems
Using rails (3.0.0.beta4) from system gems
Using sqlite3-ruby (1.3.0) from bundler gems
Your bundle is complete! Use `bundle show [gemname]` to see where a bundled gem is installed.

5. rake db:create will now work
mbp2:blog bparanj$ rake db:create
(in /Users/bparanj/projects/blog)
db/test.sqlite3 already exists

Friday, June 25, 2010

Include Vs Extend in Ruby

Include vs Extend

Include

Classes and modules can include modules and reuse the methods defined in the module. The method in the module is available as an instance method. The constants, methods and module variables are available once the module is mixed in.

Extend

You can extend an instance of any class with module. The method in the module is available as an instance method.

The difference is extend is only applicable for that particular instance which was extended. Where as the include is applicable to any instance of the class.

Screen cast IncludeExtend.mov

Addition to IncludeExtendRuby.mov

module Talkable
def talk
p "hi"
end
end

class Foo

end

Foo.extend Talkable

Foo.talk


If extend is used on the class instead of the object, the method becomes available as class method. The extend can be used inside the class or outside the class. Refer the screencast to see how it works.

Thursday, June 24, 2010

Upgrading Snow Leopard to Rails 3.0 Beta 4

1. gem env

should be 1.3.6 or above

2. gem update --system

Update Ruby gems to the latest version

3. sudo gem install i18n tzinfo builder memcache-client rack rack-test rack-mount erubis mail text-format thor bundler i18n bundler

Install required gems for Rails 3.0

4. sudo gem install rails --pre

Installs Rails 3.0 Beta 4

5. sudo mkdir /usr/local/lib/ruby/gems/1.9.1/gems/rails-3.0.0.beta4/lib

Create the lib directory to resolve the following error

ERROR: While executing gem ... (Errno::ENOENT)
No such file or directory - lib

Installing Ruby 1.9.2 on Snow Leopard

1)

Install Readline:

curl -O ftp://ftp.cwru.edu/pub/bash/readline-6.0.tar.gz
tar -xvzf readline-6.0.tar.gz
cd readline-6.0
./configure --prefix=/usr/local
make
sudo make install

I ignored the message: install: you may need to run ldconfig

2)

Install Ruby 1.9.2

curl -O ftp://ftp.ruby-lang.org/pub/ruby/1.9/ruby-1.9.2-rc1.tar.gz
tar -xvzf ruby-1.9.2-rc1.tar.gz
cd ruby-1.9.2-rc1
./configure --prefix=/usr/local --enable-pthread --with-readline-dir=/usr/local --enable-shared
make
sudo make install
sudo make install-doc


I ignored the message: configure: WARNING: unrecognized options: --with-readline-dir

3) Update ~/.bash_profile with
export PATH="/usr/local/bin:/usr/local/sbin:/usr/local/mysql/bin:$PATH"

in the last line

Open a new window and check Ruby version: ruby -v
ruby 1.9.2dev (2010-07-02 revision 28524) [x86_64-darwin10.4.0]

Wednesday, May 05, 2010

Tracking Referrals

From Google Analytics Tracking for Mobile Apps page:

The Android 1.6 OS release supports the use of a referrer URL parameter in download links to the Android Market. The Google Analytics SDK for Android uses this parameter to automatically populate referral/campaign information in Google Analytics for your application. This enables the source of the application install to be recorded and associated with future pageviews and events.

When is Steve going to provide this feature to developers for iPhone OS?

Thursday, April 22, 2010

How to convert .wav to .mp3

Use iTunes to import the .wav files. Go to preferences and change Import Settings -> Import Using to MP3 Encoder. Select all the .wav files to convert to .mp3 and go to Advanced -> Create mp3 version. Now just select one of the .wav file and go to "File -> Show in Finder", you will find all the converted mp3 files in the same folder.

You have to use iTunes to convert because the command line tool afconvert does not have the ability to convert to mp3.You will get the error Error: ExtAudioFileSetProperty ('cfmt') failed ('fmt?')

Tuesday, April 20, 2010

How to view only starred emails in Gmail

Type the following in the search box and hit search:

in:Starred in:Inbox

Migraine leaves British woman speaking with Chinese accent

"I spoke to my stepdaughter on the phone from hospital and she didn't recognize who I was. She said I sounded Chinese. Since then, I have had my friends hanging up on me because they think I'm a hoax caller ... The first few weeks of the accent was quite funny, but to think I am stuck with this Chinese accent is getting me down. My voice has started to annoy me now. It is not my voice."

Learn to speak in British Accent iPhone app:

More at National Post

Monday, April 12, 2010

How to reduce caf file size

afconvert -f caff -d LEI16@22100 -c 1 ./test.mp3 ./test.caf

I kept reducing the sampling rate from 44100 to 13100. Anything below 22100 seems to affect the quality of the audio.

You can also convert a caf file with a given sampling rate to another caf file with different sampling rate:

afconvert -f caff -d LEI16@22100 -c 1 ./test.caf ./test2.caf

Tuesday, April 06, 2010

Analyzing Your App Store Sales Statistics - Part II

AppStore Sales Vs AppViz

Clearly AppViz is the winner. Provides nice charts and downloads 13 weeks of data to your desktop and provides a clear interface.

Heartbeat Signed up for this site. After I login I don't see anything. Not easy to use or figure out how to generate reports. It takes too much time than it saves. If you have a different opinion do let me know.

Tap Mini from TapMetrics. I watched the demo. It seems to allow import. I don't like the drilling into different levels to view my data.

4 ways to capitalize on Google's real-time search results

Following tips to be tested for iPhone / iPad apps that is already in the app store.

From iMedia Connection:

To take advantage of the new real-time search results -- and minimize any potential negatives -- here are four fundamental steps for marketers:

* Keep positive messages about your brand or products alive in the online news media. Issue frequent press releases with positive news about your company and create positive viral content related to your brand or product that has the potential to be mentioned frequently on popular social networking sites and even featured in news stories.


* Be active on sites like Twitter, Facebook, MySpace, FriendFeed, Jaiku, and Identi.ca. Create positive messages about your brand or products in the online social media sites likely to appear in Google results. Promote positive news stories published on mainstream news sites that result from your press releases or viral content promotions, as well as positive viral content that you created yourself.


* Maintain an active presence in social networking and microblogging sites. Cultivate relationships and interact with influential users to enlist their help in spreading your positive message. In addition, be responsive to both positive and negative mentions of your brand or product to mitigate any negative press that may occur. (Note: This is not a job for an intern. Ensure you are represented on these sites by a professional with social media and public relations savvy.)


* Closely monitor news and real-time buzz sites for mentions of your brand or product so you can react if necessary. That means setting up accounts with Google Alerts, Yahoo Keyword News Alert, and Twitter Alerts and following them.

Monday, April 05, 2010

Analyzing Your App Store Sales Statistics

App Figures provides reporting of app sales. The graphing does not update when you change the period. Emailed the tech support. No progress has been made after a week. I do like the daily and weekly report email feature. I can set up so that all my partners get the reports emailed. The pricing seems to be reasonable: $5 / mo for 2 apps. $1.5 for each additional app that you want to track. It provides ranking of your app also.

App Sales Mobile This is available on Github. I downloaded it and ran it on Simulator. Not bad for something that is free. Nice charts and reports.

My App Sales I paid $27.70 (20 Euros) for this today. It's ok. It has lot more features. Provides data export and the option of creating html reports. I had to save the instruction to try the advanced features. The advanced features are not just one click from the app.

Friday, April 02, 2010

How to use Active Support Rails library in Ruby scripts

#!/usr/bin/ruby
require 'rubygems'
require 'active_support/inflector'

puts Inflector.singularize('inflections')

Thursday, April 01, 2010

British Accent Training iPad App is now live!

The first Accent Reduction training iPad app in the app store. British Accent Training is a great tool to help you learn British Accent. You can practice your accent, pronunciation and intonation.

Taught by a native British English speaker Alison Pitman. It gives you enough time to record, playback and to repeat the lesson.

The best solution is to practice with a computer. I tried a simple sound recorder on a computer as well as a tape recorder, and it did not work - too complicated, involves too much button pressing.

You need a program which plays a phrase, then records you repeating it, then repeats the native speaker, then plays your recording, and does it all over again in a loop until you are satisfied.

You can hear your mistakes and you feel that you are correcting them.

This training will allow you to record and hear your own voice. Record your voice every week you use the training to see the transformation in your accent.

The app demonstrates each pronunciation with practice words and sentences which are simple and easily understood. More content will be added in later releases. If you buy at current price you will get updates for free. When more content is included the price will go up. BUY NOW.

Thursday, March 25, 2010

How to prepend a character to a line

sed 's/^/"/'

will prepend the double quotes to the beginning of the text. I had to copy paste the character ^ for this to work on my Mac. Could not find on the Mac keyboard.

Monday, March 22, 2010

How to connect Windows XP machine to Mac Airport Extreme Wireless router

I bought a $150 PC from San Jose Salvation Army. It has 1 GB RAM, 40 GB hard drive with wireless card. This solves the headache of installing VMware, buying a licensed Windows and configuring etc.

First, make sure you are using WEP in your wireless router. Check the settings. If not, you have to change it to WEP in the router settings. It will prompt you for 13 character password. Once you change it, the router will reboot and the changes will be in effect. Now on your Windows machine just type the password (as alphanumeric characters, not as HEX) and you should be good to go.

Monday, March 15, 2010

Bladder Diary iPhone Released

Bladder Diary iPhone app will help you and your health care team figure out the causes of your bladder control trouble.

As long as you have your iPhone / iPod touch with you, you can record your bladder activity from anywhere and anytime.

Keeping a bladder diary (or "voiding diary") can help you and your doctor look for patterns to your bladder problems. You can track things like:

* How often you pass urine, and when
* How much urgency you feel each time
* Whether you're experiencing incontinence

You can keep a bladder diary before your appointment, or your doctor may ask you to start one to track your progress through treatment.

Export the data easily in a csv format that you can import to any spreadsheet, print it and take it to your doctor. You can also forward the data to your health care provider or anyone as an email.

The term OAB refers to "Over active bladder".

When you have Overactive Bladder (OAB), you may experience:

* Urgency: a pressing need to urinate. It can happen even when you don't really need to go. The urge can be so sudden and so strong that you have to run to the bathroom.
* Urge incontinence: when you can't reach the bathroom in time and you leak or have an accident.
* Frequency: having to urinate more than about 8 times a day.
* Nocturia: an urge to urinate that wakes you up at night

Friday, February 19, 2010

Seduction Flash Cards iPhone App

Ross Jeffries Speed Seduction(TM) Home Study Course flash cards is now available on your iPhone / iPod touch. Just swipe the flashcard to browse through 50 flash cards that consists of following themes:

1. Trance Words
2. Seduction Rules
3. Polarity Responders
4. Weasel Phrases
5. Super Influence Patterns
6. Super Weasel Phrases

Speed Seduction trademark belongs to Straight Forward Inc.

Collectible Cook Books Price Guide iPhone App

Price for over 3800 collectible cook books is now available on your finger tips. You do not need Internet connection to use this product. Due to changing nature of the market, this is not a guarantee of prices. Choose multiple research tools to verify data.

Collectible Books Price Guide iPhone App

Price for over 3000 collectible books are now available on your finger tips. You do not need Internet connection to use this product.

Due to the changing nature of the market, this is not a guarantee of prices. Choose multiple research tools to verify data.

I developed this product for my own use. Due to difficulty in getting the pricing information fast without waiting for websites to load.

Movies For Any Mood iPhone App

Top 20 movies for the genres : Action, Adventure, Animation, Biography, Comedy, Crime, Documentary, Drama, Family, Fantasy, Film-Noir, History, Horror, Independent, Music, Musical, Mystery, Romance, Sci-Fi, Short, Sport, TV Mini Series and Westerns of all time. Keep track of which movies you have watched. Search the entire database to see if it is in the top list.

Top 500 Movies iPhone App

The top 500 movies of the past 100 years is now available on your iPhone / iPod touch. You can keep track of which ones you have watched and which ones are still to be enjoyed. You can also search the entire database to find out whether it is in the top 500 list or not.

British Accent iPhone App

Boost your British accent to boost your career!

* Is your accent holding you back at work?
* Are you often asked to repeat yourself when you speak english?
* Do your friends and colleagues speak with a better British accent than you?
* Could improving your British accent improve your job prospects and get you that promotion?

then this product could help you!

If you are frustrated with your British accent and would like to speak with a clear RP voice then this video can help.

This product teaches you how to make the different sounds found in the RP British Accent.

* 15 different Vowel Sounds
* 16 different Consonant Sounds

By learning how to pronounce each of these individual sounds correctly you will be able to improve your spoken English immediately.

IMPRESS YOUR FRIENDS AND COLLEAGUES WITH YOUR REFINED BRITISH ACCENT

* Is your poor British accent affecting your job prospects?
* Could improving your British accent help improve your job opportunities?

For an investment of only $4.99 this product can help boost your British Accent to boost your promotion prospects.

iPhone App for Kidney Stones and Gallbladder Stones

iOxalate

This application is for those who have suffered from Kidney stones or Gallbladder stones due to Calcium Oxalate stones.

Foods are categorized according to the oxalate content. Foods low in oxalate can be consumed in unlimited amounts. However, common sense needs to prevail. For example, distilled alcohol, though low in oxalate, should not be consumed in unlimited quantities.

This application helps you to follow a low oxalate diet by eliminating foods very high in oxalate and eating those with moderate oxalate content in limited amounts.

This application does not have any recipes. It only contains the names of the foods categorized by oxalate content. You can also search the entire database of foods to find its oxalate content.

* Use it in a grocery store while shopping
* To lookup the food when you are in a restaurant
* When cooking to reduce the foods high in oxalate content

Monday, January 18, 2010

British Accent iPhone App now Live!

Learn British Accent on your iPhone / iPod touch: http://itunes.apple.com/us/app/british-accent/id350212768?mt=8