How to create a migration file dynamically by meta programming in rails 4.0

If you want to add a migration file from lib file or somewhere from your ruby file and execute it, use the dynamic method which can create a class or method dynamically. The following code snippet is not complete. But gives a better idea to create migration file dynamically. Use a bit of metaprogramming.

 def create_columns(tb_with_cols)
    .........
    .........
    columns.each { |column| add_columns << "\tadd_column(':#{tb_name}', :#{column})\n" }
    columns
 end

 def migration_file_content(tb_with_cols)
<<-RUBY
  class AddMissingColumnsToTable < ActiveRecord::Migration
     def change_table
    #{create_columns(tb_with_cols)}
   end
 end
  RUBY
 end


 def write_content_to_file(path, content)
    File.open(path, 'w+') do |f|
      f.write(content)
    end
 end

Just call the method ‘migration_file_content’ in your code. Pass the parameter tb_with_cols as a Hash whose key is the table_name and value is the columns that should be added to that table like:

tb_with_cols = {:users => {:name => :string, :age => :integer, :address => :text} }

After that just call the method ‘write_content_to_file’ with your new migration file path and the content from our ‘migration_file_content’ method. 🙂

Advertisements

Rails way of creating a new full url with new parameters after removing old parameters from a url

If we have some keys and values and we just need to create a url with this data just pass the url and hash as a parameter to the following method.

def generate_url_with_params(url, params = {})
    uri = URI(url)
    uri.query = params.to_query
    uri.to_s
end

If you want to get rid of the parameters from a url use the following method.

  def generate_url_without_params(url, params = {})
    uri = URI(url)
    full_params = Rack::Utils.parse_query uri.query
    params.each do |key, val|
      full_params.delete key
    end
    uri.query = full_params.to_param
    uri.to_s
  end

How to implement a simple captcha in Rails using gem ‘simple_captcha’

Here it is, a simple captcha for Rails applications.

To set up, add the following line to your Gemfile

gem "galetahub-simple_captcha", :require => "simple_captcha"

Run rails generator

rails generate simple_captcha

Do db Migration

rake db:migrate -t

In your view file add

%= show_simple_captcha %

Add the following in yml file
en.yml:

en:
  simple_captcha:
    label: "Enter the above code"
    placeholder: "Enter here"

In controller just include captcha helpers module

class ApplicationController < ActionController::Base
  include SimpleCaptcha::ControllerHelpers
end

Use this code in the controller for the captcha validation

if simple_captcha_valid?
  do this
else
  do that
end

Details about pg gem error: Can’t find the ‘libpq-fe.h header when doing bundle in Rails

If you are getting errors like:

installing pdf-reader 1.3.3
Gem::Ext::BuildError: ERROR: Failed to build gem native extension.

/home/vagrant/.rvm/rubies/ruby-2.2.0/bin/ruby -r ./siteconf20150306-5919-1rr483p.rb extconf.rb
checking for pg_config... yes
Using config values from /usr/bin/pg_config
You need to install postgresql-server-dev-X.Y for building a server-side extension or libpq-dev for building a client-side application.
You need to install postgresql-server-dev-X.Y for building a server-side extension or libpq-dev for building a client-side application.
checking for libpq-fe.h... no
Can't find the 'libpq-fe.h header
*** 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.

when trying to install pg gem,
you are just missing some dependancy library related to libpq. Install the following package


$ sudo apt-get install libpq-dev

then do


$ gem install pg -v 'version-no'

then do


bundle install

Details about paperclip error: ‘Paperclip::AdapterRegistry::NoHandlerError’ when you use paperclip gem in Rails

When I was working with rails and paperclip I got this error.

Paperclip::AdapterRegistry::NoHandlerError
 = form_tag my_path, :method => :post do
  -------
  = file_field_tag "attachment" 
  -----
 

I submitted a form and it was not saving. There I found that the form sending a file too. I missed

:multipart => true 

option in the ‘form_tag’ when submitting the form. The form really not sening a file and paperclip not getting an attachment. So it throws this error.

 = form_tag my_path, :method => :post, :multipart => true do
  -------
  = file_field_tag "attachment" 
  -----

How to find index of records rendered by a partial with collection in Rails

Using render partial with collection how to find the index of the records?

Somewhere I found that someone is commented like,
“It seems this is an undocumented feature of rails.”

Anyway we can find this by using ‘recordName_counter’.

Render a partial with collection


= render :partial = > "person", :collection => @winners
Name: = person.name 

In Partial write


  Rank: = person_counter + 1
  Name: = person.name 

Result


Rank: 1 Name: Peter
Rank: 2 Name: Paul
Rank: 3 Name: Mary

Details about Rails paperclip error: ‘There was an error processing the thumbnail for paperclip-reprocess’

I got this error while working with paperclip. The project was stable and I have no idea why this error happens at this point of time.

[paperclip] An error was received while processing: #
[paperclip] An error was received while processing: #<Paperclip::PaperclipError: There was an error processing the thumbnail for paperclip-reprocess20110822-2281-19969sz

So I was lazy to fix the error, and find that I have no imagemagick installed in my new system. After installing ‘imagemagick’ it got fixed.

$ sudo apt-get update
$ sudo apt-get install imagemagick --fix-missing