Posts

Showing posts from 2012

How to use arguments with before filter with other options

How to use arguments with before filter with other options Lets suppose you have a method in the application controller "find_instance" that you wanted to use as before filter with an added argument "category" .So use the below mentioned code. before_filter { |c| c.find_instance 'category' } If you waned to add more options to your before filter do something like this. before_filter(:except=>[:index,:new,:create]) { |c| c.find_instance 'category' } And then in the application controller you do something like this def find_instance(obj) instance = obj.camelize.constantize.find(params[:id]) instance_variable_set("@#{obj}",instance)  end It will give you @category as an instance variable which will become @category = Category.find(params[:id])

Generate Scaffold for already Existing files

Generate Scaffold for already Existing files. First you can check all the exiting options available to you by using a following command. rails generate -h if you'd like to generate a controller scaffold for your model, you can use scaffold_controller you can also use --skip option to skip any files which exist.

Procs , Lambda and their difference

Procs  Like variables hold data, procs hold the code itself. example_proc = Proc.new{ puts “I am a Example” } We will use proc by using .call method example_proc.call lambda { foo } and proc { foo } is essensially the same thing, you can use both interchangeable in your code. There are couple of differences which are as follows One of the main difference and major difference between them is that  Proc object does not care at all for the number of arguments you pass to it e.g. p = proc{|a,b| p "The value of a is #{a.inspect}. The value of b is #{b.inspect}"}   p.call 1,2 # => "The value of a is 1. The value of b is 2"   p.call 1 # => "The value of a is 1. The value of b is nil"   p.call 1,[2,3],Class.new # => "The value of a is 1. The value of b is [2,3]"   So , it takes the first two arguments and discards the rest but if we pass  less than two it will assume that the other(s) are nil l = lambda{|a,b| p "Th

PostgreSql : Most common issues

Installation To install PostgreSQL, run the following command in the command prompt: sudo apt-get install postgresql Test the installation by following command here 8.3 is the version which i am using sudo /etc/init.d/postgresql-8.3 restart Now that we can connect to our PostgreSQL server, Please make sure that you restart the server after making the below mentioned changes, the next step is to set a password for the postgres user. Run the following command at a terminal prompt to connect to the default PostgreSQL template database: sudo -u postgres psql template1 The above command connects to PostgreSQL database template1 as user postgres. Once you connect to the PostgreSQL server, you will be at a SQL prompt. You can run the following SQL command at the psql prompt to configure the password for the user postgres. ALTER USER postgres with encrypted password 'your_password'; Now you can also use the PGADMIN for the GUI with the following mentioned username and password.

Multiple Skype Instance on MAC (Snow Leopard)

Run the following command to open another instance of skype sudo /Applications/Skype.app/Contents/MacOS/Skype

Install ImageMagick on MAC (Snow Leopard)

Install MAC Ports (Download the .dmg file from macports website , install it and restart your system) Then run the following commands. sudo port install tiff -macosx imagemagick +q8 +gs +wmf Install Gem sudo gem install rmagick

Converting One Image Format to Another using Ruby

Insert the following code in your Ruby file. require 'rubygems' require 'RMagick' img = Magick::Image.read("image.png").first img.write("image.jpg") # Writes a JPEG img.write("image.gif") # Writes a GIF img.write("JPG:image") # Writes a JPEG img.write("JPG:image.gif") # Writes a JPEG

Re-Crop Image using Jcrop and Paperclip

For the people who wanted to crop an image twice or wanted to give users an option to re-crop the image without uploading it again. So here it is by the below mentioned code , only the small image will be cropped and you can use large to show the user an option to re-corp without hurting the cropping ratio. So In your model you need to mention : :styles => { :small => "150x150#", :large => "400x400>" }, :processors => [:cropper] And the change which you need to make is : :styles => { :small => {:geometry => "150x150#", :processors => [:cropper]}, :large => {:geometry => "400x400>"} }

Active Admin

Image
Active Admin Documentation Active Admin is a framework for creating administration style interfaces. It abstracts common business application patterns to make it simple for developers to implement beautiful and elegant interfaces with very little effort. An elegant DSL built for developer productivity. Get started with one line of code or customize the entire interface with the provided DSL . # app/admin/posts.rb ActiveAdmin . register Product do # Create sections on the index screen scope :all , :default => true scope :available scope :drafts # Filterable attributes on the index screen filter :title filter :author , :as => :select , :collection => lambda { Product . authors } filter :price filter :created_at # Customize columns displayed on the index screen in the table index do column :title column "Price" , :sortable => :price do | product | numb

MySQL couldn't find log file on Snow leopard

If you have removed the Binary logs from the file system that exits in the mysql data folder and during the start up an error will occur These is after tailing the error log of mysql. /usr/sbin/mysqld: File './mysql_bin.000025' not found (Errcode: 2) [ERROR] Failed to open log (file './9531_mysql_bin.000025', errno 2) [ERROR] Could not open log file [ERROR] Can't init tc log [ERROR] Aborting InnoDB: Starting shutdown... InnoDB: Shutdown completed; log sequence number 0 2423986213 [Note] /usr/sbin/mysqld: Shutdown complete Basically, MySQL is looking in the mysql-bin.index file and it cannot find the log files that are listed within the index. This will keep MySQL from starting, but the fix is quick and easy. You have two options: Edit the index file You can edit the mysql-bin.index file in a text editor of your choice and remove the references to any logs which don't exist on the filesystem any longer. Once you're done, save the index file and start

Difference between "and" : "&&" in Ruby

and v/s && Many people seem to prefer using and instead of && in Ruby, as it sounds more like speech. However, do note that it’s slightly different from using &&. The difference is important enough that I think you should avoid using and. && (double ampersand) vs and The difference is that && has higher precedence. This means that it will get evaluated before and. So, we end up with weird stuff in some situations. This is perhaps most likely to cause weirdness when using the ternary operator, as it is evaluated before and. Here’s a real life example: >> a = true >> b = false # 1 >> a and b ? 'hello' : '**silence**' => "**silence**" # 2 >> a && b ? 'hello' : '**silence**' => "**silence**" # 3 >> b and a ? 'hello' : '**silence**' => false # oops # 4 >> b && a ? 'hello' : '**silence**' =>

How to change the TimeStamp using RUBY

For Changing the TimeStamp we are going to use touch FileUtils.touch 'sample.txt', :mtime => Time.now - 2.hours If you omit the :mtime the modification timestamp will be set to the current time: FileUtils.touch 'sample.txt' You may also pass an array of filenames: FileUtils.touch %w[ foo bar baz ], :mtime => Time.now - 2.hours Non-existent files will be created.

Generate abbreviations from string

Generate abbreviations from string >> str = "nishant nigam" => "nishant nigam" >> str.split(" ").map {|name| name[0].chr }.join.upcase => "NN"

Compression Related Commands

tar cf file.tar files – create a tar named file.tar containing files tar xf file.tar – extract the files from file.tar tar czf file.tar.gz files – create a tar with Gzip compression tar xzf file.tar.gz – extract a tar using Gzip tar cjf file.tar.bz2 – create a tar with Bzip2 compression tar xjf file.tar.bz2 – extract a tar using Bzip2 gzip file – compresses file and renames it to file.gz gzip -d file.gz – decompresses file.gz back to file

Process Management by Commands on Unix/Linux

Process Management ps – display your currently active processes top – display all running processes kill pid – kill process id pid killall proc – kill all processes named proc * bg – lists stopped or background jobs; resume a stopped job in the background fg – brings the most recent job to foreground ping host – ping host and output results fg n – brings job n to the foreground

Basic File Related Linux/Unix Commands

ls – directory listing ls -al – formatted listing with hidden files cd dir - change directory to dir cd – change to home pwd – show current directory mkdir dir – create a directory dir rm file – delete file rm -r dir – delete directory dir rm -f file – force remove file rm -rf dir – force remove directory dir * cp file1 file2 – copy file1 to file2 df – show disk usage free – show memory and swap usage mv file1 file2 – rename or move file1 to file2 whereis app – show possible locations of app touch file – create or update file cat > file – places standard input into file more file – output the contents of file head file – output the first 10 lines of file tail file – output the last 10 lines of file tail -f file – output the contents of file as it

Error libxml2 is missing while Installing Nokogiri

Error gem install nokogiri Installing nokogiri (1.5.0) with native extensions Gem::Installer::ExtensionBuildError: ERROR: Failed to build gem native extension. /home/user/.rvm/rubies/ruby-1.9.2-p290/bin/ruby extconf.rb checking for libxml/parser.h... no ----- libxml2 is missing. please visit http://nokogiri.org/tutorials/installing_nokogiri.html for help with installing dependencies. ----- *** extconf.rb failed *** Could not create Makefile due to some reason, probably lack of necessary libraries and/or headers. Check the mkmf.log file for more details. You may need configuration options. Provided configuration options: --with-opt-dir --with-opt-include --without-opt-include=${opt-dir}/include --with-opt-lib --without-opt-lib=${opt-dir}/lib --with-make-prog --without-make-prog --srcdir=. --curdir --ruby=/home/user/.rvm/rubies/ruby-1.9.2-p290/bin/ruby --with-zlib-dir --without-zlib-dir --with-zlib-include --without-zlib-include=${zlib-dir}/include --with-z

Error : xcode-debugopt while installing ruby version with RVM

rvm install 1.9.3-p125   Installing Ruby from source to: /home/user/.rvm/rubies/ruby-1.9.3-p125, this may take a while depending on your cpu(s)... ruby-1.9.3-p125 - #fetching ruby-1.9.3-p125 - #extracted to /home/user/.rvm/src/ruby-1.9.3-p125 (already extracted) Applying patch 'xcode-debugopt-fix-r34840' (located at /home/user/.rvm/patches/ruby/1.9.3/p125/xcode-debugopt-fix-r34840.diff) Error running 'patch -F 25 -p1 -N -f <"/home/user/.rvm/patches/ruby/1.9.3/p125/xcode-debugopt-fix-r34840.diff"', please read /home/user/.rvm/log/ruby-1.9.3-p125/patch.apply.xcode-debugopt-fix-r34840.log rvm requires autoreconf to install the selected ruby interpreter however autoreconf was not found in the PATH.    Solution sudo apt-get install automake

Gemfile Options

You can do any of the following in the Gemfile: gem "name", "version" : version may be a strict version or a version requirement like &gt;= 1.0.6 . The version is optional. gem "name", "version", :require_as =&gt; "file" : the require_as allows you to specify which file should be required when the require_env is called. By default, it is the gem’s name gem "name", "version", :only =&gt; :testing : The environment name can be anything. It is used later in your require_env call. You may specify either :only , or :except constraints gem "name", "version", :git =&gt; "git://github.com/wycats/thor" : Specify a git repository to be used to satisfy the dependency. You must use a hard dependency (“1.0.6″) rather than a soft dependency (“>= 1.0.6″). If a .gemspec is found in the repository, it is used for further dependency lookup. If the repository has multiple

Error Installing Mysql Gem on Mac Snow Leopard

Gem::Installer::ExtensionBuildError: ERROR: Failed to build gem native extension. /Users/abc/.rvm/rubies/ruby-1.9.2-p318/bin/ruby extconf.rb checking for mysql_query() in -lmysqlclient... no checking for main() in -lm... yes checking for mysql_query() in -lmysqlclient... no checking for main() in -lz... yes checking for mysql_query() in -lmysqlclient... no checking for main() in -lsocket... no checking for mysql_query() in -lmysqlclient... no checking for main() in -lnsl... no checking for mysql_query() in -lmysqlclient... no checking for main() in -lmygcc... no checking for mysql_query() in -lmysqlclient... no *** extconf.rb failed *** Could not create Makefile due to some reason, probably lack of necessary libraries and/or headers. Check the mkmf.log file for more details. You may need configuration options. Provided configuration options: --with-opt-dir --with-opt-include --without-opt-include=${opt-dir}/include --with-opt-lib --

Everything you need to know about Migrations

Methods: create_table(name, options) drop_table(name) rename_table(old_name, new_name) add_column(table_name, column_name, type, options) rename_column(table_name, column_name, new_column_name) change_column(table_name, column_name, type, options) remove_column(table_name, column_name) add_index(table_name, column_name, index_type) remove_index(table_name, column_name) change_table(table_name) {|Table.new(table_name, self)| ...} change_column_default(table_name, column_name, default) change_column_null(table_name, column_name, null, default = nil) Available Column Types (mappings are below): * integer * float * datetime * date * timestamp * time * text * string * binary * boolean * decimal :precision, :scale Valid Column Options: * limit * null (i.e. ":null => false" implies NOT NULL) * default (to specify default values) * :decimal, :precision => 8, :s

Install Ruby on Rails on Ubuntu

First we need to make sure that the system which we are using is up to date , so for that run the command below sudo apt-get update We'll be installing some software that needs to be built so we'll need to get packages required for compiling. With Ubuntu, you can type this single command and get everything you need: sudo apt-get install build-essential   Once you've got the tools, it's time to install MySQL and Ruby sudo apt-get install ruby ri rdoc mysql-server libmysql-ruby ruby1.8-dev irb1.8 libmysql-ruby1.8 libreadline-ruby1.8 libruby1.8 mysql-client-5.1 mysql-common mysql-server-5.1 rdoc1.8 ri1.8 ruby1.8 irb libopenssl-ruby libopenssl-ruby1.8 mysql-server-core-5.1 libmysqlclient16 libreadline5 psmisc If you hadn't previously installed MySQL you'll be asked to set a root password. You don't have to, of course (it will bug you no fewer than 3 times if you opt not to) but I strongly recommend it. You'll need this password when you populate your

Install Debugger in Ruby 1.9.3

Download newer versions linecache19-0.5.13.gem and ruby-debug-base19-0.11.26.gem from http://rubyforge.org/frs/?group_id=8883 $ gem install ~/Downloads/linecache19-0.5.13.gem -- --with-ruby-include=$rvm_path/src/ruby-1.9.3-p0 Building native extensions. This could take a while... Successfully installed linecache19-0.5.13 1 gem installed   $ gem install ~/Downloads/ruby-debug-base19-0.11.26.gem -- --with-ruby-include=$rvm_path/src/ruby-1.9.3-p0 Building native extensions. This could take a while... Successfully installed ruby-debug-base19-0.11.26 1 gem installed   Add these in your gemfile gem 'linecache19', '0.5.13' gem 'ruby-debug-base19' gem 'ruby-debug19', :require => 'ruby-debug'   if this doesn't work try this gem 'linecache19', '0.5.13', :path => "~/.rvm/gems/ruby-1.9.3-p0/gems/linecache19-0.5.13/" gem 'ruby-debug-base19', '0.11.26', :path => "~/.rvm/gems/ruby-1.9.3-p0/ge

Automating Tasks with Rake

Rake is available as the rake gem; if you've installed Rails, you already have it. Unlike most gems, it doesn't just install libraries: it installs a command-line program called rake, which contains the logic for actually performing Rake tasks. A Rakefile is just a Ruby source file that has access to some special methods: task, file, directory, and a few others. Calling one of these methods defines a task, which can be run by the command-line rake  program, or called as a dependency by other tasks. The most commonly used method is the generic one: task. This method takes the name of the task to define, and a code block that implements the task. Here's a simple Rakefile that defines two tasks, cross_bridge  and build_bridge, one of which depends on the other. It designates cross_bridge as the default task by defining a third task called default which does nothing except depend on cross_bridge. # Rakefile desc "Cross the bridge." task :cross_bridge =>

Stashing in Git

The Below are the basic commands along with there description     git stash   git stash save <optional-name> save your local modifications to a new stash (so you can for example "git svn rebase" or "git pull") git stash apply restore the changes recorded in the stash on top of the current working tree state git stash pop restore the changes from the most recent stash, and remove it from the stack of stashed changes git stash list list all current stashes git stash show <stash-name> -p show the contents of a stash - accepts all diff args git stash drop [<stash-name> ] delete the stash git stash clear delete all current stashes

RVM : Ruby Version Manager : A Complete Guide

Install RVM   bash < <( curl http://rvm.beginrescueend.com/releases/rvm-install-head ) Show all rubies and gemsets rvm list gemsets Upgrade to the latest version of rvm from github rvm update --head   Ruby on Rails 3 Tutorial says to follow this with     rvm reload     rvm install 1.8.7     rvm install 1.9.2   and, if you need a patchlevel, do something like       rvm install 1.8.7-p174   Install a given version of ruby     rvm install 1.9.2   If this fails with compiler errors, you may need to install some packages.       rvm package install openssl     rvm package install readline     rvm package install iconv     rvm install 1.9.2 --with-openssl-dir=$HOME/.rvm/usr \       --with-readline-dir=$HOME/.rvm/usr \       --with-iconv-dir=$HOME/.rvm/usr     On Mac, you may need to install some libraries via MacPorts.       sudo port install ncurses     sudo port install libyaml     sudo port install zlib      rvm install 1.9.2 --with-libyaml-dir=/opt/loca

Simulating Multiple Inheritance with Mixins

You want to create a class that derives from two or more sources, but Ruby doesn't support  multiple inheritance in such cases you can use mixins A Ruby class can only have one superclass, but it can include any number of modules. These modules are called  mixins. If you write a chunk of code that can add functionality to classes in general, it should go into a mixin module instead of a class. The only objects that need to be defined as classes are the ones that get instantiated and used on their own (modules can't be instantiated). When a class includes a module with the include keyword, all of the module's methods and constants are made available from within that class. They're not copied, the way a method is when you alias it. Rather, the class becomes aware of the methods of the module. If a module's methods are changed later (even during runtime), so are the methods of all the classes that include that module. Below is the simple example. Suppose

Basics Of Ruby Hashes

Hashes and arrays are the two basic "aggregate" data types supported by most modern programming languages. The basic interface of a hash is similar to that of an array. The difference is that while an array stores items according to a numeric index, the index of a hash can be any object at all. empty = Hash.new # => {} empty ={} # => {} numbers = { 'two' => 2, 'eight' => 8} # => {"two"=>2, "eight"=>8} numbers = Hash['two', 2, 'eight', 8] # => {"two"=>2, "eight"=>8} Once the hash is created, you can do hash lookups and element assignments using the same syntax you would use to view and modify array elements: numbers["two"] # => 2 numbers["ten"] = 10 # => 10 numbers # => {"two"=

Configuring Rails to Send Email

Add the following code to config/environment.rb: ActionMailer::Base.server_settings = {   :address        => "mail.yourhostingcompany.com",   :port           => 25,   :domain         => "www.yourwebsite.com",   :authentication => :login,   :user_name      => "username",   :password       => "password" } Replace each hash value with proper settings for your Simple Mail Transfer Protocol (SMTP) server. You may also change the default email message format. If you prefer to send email in HTML instead of plain text format, add the following line to config/environment.rb as well: ActionMailer::Base.default_content_type = "text/html" Possible values for ActionMailer::Base.default_content_type are "text/plain", "text/html", and "text/enriched". The default value is "text/plain". ActionMailer::Base.server_settings is a hash object containing configuration parameters to connec

Many to Many associations in Rails HABTM and has_many :through

We've noticed there's a bit of confusion about the differences between the two ways to create many-to-many relationships using Rails associations.  Has and Belongs to many (HABTM) or Join Table Associations create_table "dancers_movies", :id => false do |t| t.column "dancer_id", :integer, :null => false t.column "movie_id", :integer, :null => false end class Dancer < ActiveRecord::Base has_and_belongs_to_many :movies end class Movie < ActiveRecord::Base has_and_belongs_to_many :dancers end   has_and_belongs_to_many associations are simple to set up. The join table has only foreign keys for the models being joined - no primary key or other attributes.There is no model class for the join table. has many : through or Join Model associations create_table "appearances", do |t| t.column "dancer_id", :integer, :null => false t.column "movie_id", :integer, :null =>

Prototype, and JQuery inside Rails Application

It has become common practice to use JQuery as the javascript library of choice for Ruby on Rails  applications with the latest versions of rails using JQuery.  But If you have an Rails application that is already using Prototype, it may create problems to replace that with JQuery . And sometimes, you just simply need both to work at the same time. Use Prototype/Scriptaculous with JQuery  First, in our application layout, we’re going to get rid of <% = javascript_include_tag :defaults %> and include each javascript file explicitly just to make things a little easy to understand and a little more straight forward.  So we have replaced defaults with  <%= javascript_include_tag 'prototype', 'scriptaculous', 'application' %> Now, we’ll add in JQuery, by downloading the latest version of JQuery from the JQuery Download page from the JQuery Website <%= javascript_include_tag 'prototype', 'scriptaculous', '

Convert Pdf to Swf with SWFTools and Intallation on Linux Ubuntu

Installation And Usage First you need to download the SWFTools for SWF manipulation and generation , for that you can directly download from here Or Take a Git Clone   git clone git://git.swftools.org/swftools   So these are the steps you need to follow tar -zvxf swftools-0.x.x.tar cd swftools-0.x.x ./configure make make install   You also need to install few libraries, You can directly install these from Ubuntu Software Center , if you are using Ubuntu  freetype jpeglib Now type this to confirm the installation whereis pdf2swf   Once you have the location, you will be ready with the command whereis pdf2swf pdf2swf: /usr/bin/pdf2swf /usr/share/man/man1/pdf2swf.1.gz Now you are on the way to use the command to covert pdf to swf /usr/bin/pdf2swf -zl -p 1-10 -s bitmap -j 75 --viewer /path_to_background.swf /path_to_pdf_file.pdf -o /Output_pdf.swf

Sending Binary Data over the Network with Json

First, you need to open the file. Since the file is binary, you have to open it with an additional “b” flag. Here i am sending a zip file f = File.open("path/myzip.zip", "rb")   Next, you have to do binary-to-text encoding on the binary file because the JSON will complain if you try to feed it a binary string. To overcome this obstacle, you need to apply Base64 encoding. file_content = Base64.b64encode(f.read())   After you have a text representation of the data, you can then use JSON to package it, you can use to_json to convert in to json {:file=>file_content}.to_json In your  Rails application you can do this like render :layout=>false , :json => {:file=> file_content}.to_json

What is the Role of HTML5 in Rails 3

We’ve all heard that Rails 3 uses HTML5. That’s true, but the actual role that HTML5 plays in Rails 3 applications may be simpler than you suspect. Before that you need to know few things What rails.js does It finds remote links, forms, and inputs, and overrides their click events to submit to the server via AJAX. It triggers six javascript events to which you can bind callbacks to work with and manipulate the AJAX response. Remember the first thing rails.js does? Before it can override the click and submit events of all the remote elements, it first needs to find all the remote elements. Rails 3 takes advantage of this new valid markup, by turning all links and forms with :remote => true into HTML elements that have the tag data-remote=true. <%= link_to "home", {:action => "index"}, :remote => true, :class => "button-link" %> # => <a href="index" class="button-link" data-remote