Pages

Monday, 16 November 2015

Build gem from Scratch

$ bundle gem lorem
      create  lorem/Gemfile
      create  lorem/Rakefile
      create  lorem/.gitignore
      create  lorem/lorem.gemspec
      create  lorem/lib/lorem.rb
      create  lorem/lib/lorem/version.rb

Initializating git repo in /Users/eifion/code/ep245/lorem

The bundle gem command creates a new directory and generates several files in it. It also initializes a git repository there. This assumes that you’re using git and we’ll explain why it does this shortly. Before we do that we’ll walk you through some of the generated files, starting with the lorem.gemspec file.

/lorem/lorem.gemspec

# -*- encoding: utf-8 -*-
$:.push File.expand_path("../lib", __FILE__)
require "lorem/version"
 
Gem::Specification.new do |s|
  s.name        = "lorem"
  s.version     = Lorem::VERSION
  s.platform    = Gem::Platform::RUBY
  s.authors     = ["TODO: Write your name"]
  s.email       = ["TODO: Write your email address"]
  s.homepage    = ""
  s.summary     = %q{TODO: Write a gem summary}
  s.description = %q{TODO: Write a gem description}
 
  s.rubyforge_project = "lorem"
 
  s.files         = `git ls-files`.split("\n")
  s.test_files    = `git ls-files -- ↵
    {test,spec,features}/*`.split("\n")
  s.executables   = `git ls-files -- bin/*`.split("\n").map{ ↵
    |f| File.basename(f) }
  s.require_paths = ["lib"]
end

We can see straight away by looking at the TODO items that this file is designed to be edited directly. Once we complete these items we’ll have a working Gemspec file. One interesting part of this file are the file attributes towards the end of the file. Each of these is determined at runtime by using the git ls-files command by using git to determine the files that will be included in the gem and this is why bundle gem creates a git repository. The good thing about this is that it will automatically inherit the behaviour of the .gitignore file so that temporary files and the files we don’t want in our git repository (and therefore don’t want in our gem) are excluded. The defaults above will work for most gems but they can always be edited if we need different behaviour.

Another thing to note is how the version number is determined. This is defined as a constant called Lorem::VERSION and this value is defined in another file called version.rb in the lib/lorem directory. All this file does is define the version number.

/lib/lorem/version.rb
module Lorem
  VERSION = "0.0.1"
end
When it’s time to update our gem to a new version we can change the version number here and republish the gem.

The other file generated in the lib directory is called lorem.rb and it’s this file that’s loaded when someone requires our gem. We can put any code we like in this file or create other files in the lib directory and require them here. For our simple Lorem gem we’ll just create a class method called ipsum that returns some Lorem Ipsum text.

/lib/lorem.rb
module Lorem
  def self.ipsum
    "Lorem ipsum dolor sit amet, consectetur adipisicing ...."
  end
end
Publishing

So, we’ve finished our gem now and we’re ready to publish the first version. Before we do we’ll update the Gemspec file and replace the TODO text.

/lorem.gemspec
# -*- encoding: utf-8 -*-
$:.push File.expand_path("../lib", __FILE__)
require "lorem/version"
 
Gem::Specification.new do |s|
  s.name        = "lorem"
  s.version     = Lorem::VERSION
  s.platform    = Gem::Platform::RUBY
  s.authors     = ["Eifion Bedford"]
  s.email       = ["eifion@asciicasts.com"]
  s.homepage    = ""
  s.summary     = %q{Lorem ipsum generator}
  s.description = %q{Simply generates lorem ipsum text.}
 
  s.rubyforge_project = "lorem"
 
  s.files         = `git ls-files`.split("\n")
  s.test_files    = `git ls-files -- {test,spec,features}/*`.split("\n")
  s.executables   = `git ls-files -- bin/*`.split("\n").map{ |f| File.basename(f) }
  s.require_paths = ["lib"]
end
Then we can run the gem build command and point it to our Gemspec file.

$ gem build lorem.gemspec
WARNING:  no homepage specified
  Successfully built RubyGem
  Name: lorem
  Version: 0.0.1
  File: lorem-0.0.1.gem
This command generates a .gem file. If we were to run the gem push command now that would push the gem up to RubyGems.org and publish it so that others could install it.


Rails Deployment on Centos/Redhat

Centos
-------

$ yum -y update

Install the bundle containing development tools by executing the following command:

$ yum groupinstall -y 'development tools'

Some of the packages we need for this tutorial (e.g. libyaml-devel, nginx etc.) are not found within the official CentOS repository.

Run the following to add the EPEL repository:

$ sudo su -c 'rpm -Uvh http://dl.fedoraproject.org/pub/epel/6/x86_64/epel-release-6-8.noarch.rpm'

$ yum -y update

Finally, in order to install some additional libraries and tools, run the following command:

$ yum install -y curl-devel nano sqlite-devel libyaml-devel

$ curl -L get.rvm.io | bash -s stable

$ source ~/.profile
$ rvm reload

$ rvm requirements
(if got error "Requirements installation failed with status: 1")

$ rvm install 1.8.7

Close the connection and relogin to remove the error: RVM is not a funciton

$ rvm use 1.8.7-p374 --default

$ yum install git

---------------------------------------------------------------------------------------------

MySQL Install

To begin with, a simple MySQL install:


$ sudo yum install mysql-server mysql mysql-devel


Note that we have installed the development libs and headers with the 'mysql-devel' package. This package is required by the mysql Rubygems package which we install later in this article.
Start

We need to start the MySQL server to intiliaze the installation of the base MySQL databases.

$ sudo /etc/init.d/mysqld start

--------------------------------------------------------------------------------------------------------------


$ gem install passenger --no-ri --no-rdoc

$ yum install curl-devel httpd-devel 

The environment is now ready for the compilation. The process takes a few minutes and it’s started by the following command:

Unbale to restart the server

$ sudo chmod o+x "/home/user"

$ passenger-install-apache2-module  

$ ssh-keygen

$ cat id_rsa.pub >> ~/.ssh/authorized_keys

Note: once you've imported the public key, you can delete it from the server.

and finally set file permissions on the server:

$ chmod 700 ~/.ssh
$ chmod 600 ~/.ssh/authorized_keys 

The above permissions are required if StrictModes is set to yes in /etc/ssh/sshd_config (the default).

Ensure the correct SELinux contexts are set:

$ restorecon -Rv ~/.ssh 

Now when you login to the server you won't be prompted for a password (unless you entered a passphrase when you created your key pair). By default, ssh will first try to authenticate using keys. If no keys are found or authentication fails, then ssh will fall back to conventional password authentication.

Once you've checked you can successfully login to the server using your public/private key pair, you can disable password authentication completely by adding the following setting to your /etc/ssh/sshd_config file:

# Disable password authentication forcing use of keys

PasswordAuthentication no

# Enter home directory
cd

#Give permissions

sudo chown -R user:user /path/to/direcrtory        #directory should be application deployment folder
sudo chmod -R g+w /path/to/directory


Create a new virtual host for your application.

Open the /etc/httpd/conf/httpd.conf file and uncomment the following line

NameVirtualHost *:80
At the end of the file, add

<VirtualHost *:80>
   ServerName yourdomain.com
   ServerAlias www.yourdomain.com
   DocumentRoot /home/newUser/my_rails_app/public
   <Directory /home/newUser/my_rails_app/public>
      AllowOverride all
      Options -MultiViews
   </Directory>
  ErrorLog /var/log/httpd/my_rails_app_error.log
  CustomLog /var/log/httpd/my_rails_app_access.log common
</VirtualHost>
Restart apache for the changes to take effect

sudo /etc/init.d/httpd restart

-----------------------------------------------------------------------------------------------------------------------------

Add Gem to your Gemfile
gem 'capistrano'

$ capify .

 Unable to start the Phusion Passenger watchdog because


Permission denied on rvm folder
chcon -R -h -t httpd_sys_script_exec_t /home/user/.rvm/

Getting error:
Starting httpd: Warning: DocumentRoot [/home/user/apps/alc/current/public] does not exist
Solution
 sudo setsebool -P httpd_enable_homedirs 1

 sudo visudo

nano /etc/httpd/conf/httpd.conf
add this conf on httpd.conf
ServerName 127.0.0.1


--------------------------------------------------------------------------------------------------------------------------


Set Up on REDHAT
----------------

yum -y update

Install the bundle containing development tools by executing the following command:

yum groupinstall -y 'development tools'

yum install gcc-c++ patch readline readline-devel zlib zlib-devel
yum install libyaml-devel libffi-devel openssl-devel make
yum install bzip2 autoconf automake libtool bison iconv-devel

gpg --keyserver hkp://keys.gnupg.net --recv-keys D39DC0E3  #if got error: GPG signature verification failed for

curl -L get.rvm.io | bash -s stable

source /etc/profile.d/rvm.sh


---------------------------------------------------------------------------------------------

MySQL Install

To begin with, a simple MySQL install:


sudo yum install mysql-server mysql mysql-devel


Note that we have installed the development libs and headers with the 'mysql-devel' package. This package is required by the mysql Rubygems package which we install later in this article.
Start

We need to start the MySQL server to intiliaze the installation of the base MySQL databases.

sudo /etc/init.d/mysqld start

yum install curl-devel httpd-devel



Understanding on Singleton

Code for singleton pattern

require "singleton"

class SimpleLogger
  include Singleton

  def initialize
    @output = []
  end

  attr_reader :output

  def error(message)
    output << formatted_message(message, "ERROR")
  end

  def info(message)
    output << formatted_message(message, "INFO")
  end

  def write(filename)
    File.open(filename, "a") { |f| f << output.join }
  end

  private

  def formatted_message(message, message_type)
    "#{Time.now} | #{message_type}: #{message}\n"
  end
end

Upgradation rails 2 to rails 4 (Errors)

Some Errors are given below while migration of rails 2 to rails 4
  • 'rake/rdoctask' is obsolete and no longer supported. Use 'rdoc/task' (available in RDoc 2.4.2+) instead.
require 'rake/rdoctask'
to
require 'rdoc/task'
  • undefined method `attr_accessible' for
Add ‘gem 'protected_attributes' to Gemfile
  • undefined method `link_to_function' for
Add patch in app/helpers/link_to_helper_function.rb

module LinkToFunctionHelper def link_to_function(name, *args, &block) html_options = args.extract_options!.symbolize_keys function = block_given? ? update_page(&block) : args[0] || '' onclick = "#{"#{html_options[:onclick]}; " if html_options[:onclick]}#{function}; return false;" href = html_options[:href] || '#' content_tag(:a, name, html_options.merge(:href => href, :onclick => onclick)) end end
  • ActiveRecord::AssociationNotFoundError (Association named 'authorizations' was not found on User
Change in lib/authenticated_system.rb:108 to (if using restful-authentication)


User.includes(:roles => :authorizations).find_by_id(session[:user_id])

  • undefined method `has_strings' for
Comment has_string wherever you find it.

  • Unknown key: :order. Valid keys are: :class_name, :class, :foreign_key…
Change format something like that


has_many :commission_reports, :order => "volume_year DESC, volume_month DESC", :dependent => :destroytohas_many :commission_reports, -> { order "volume_year DESC, volume_month DESC" }, dependent: :destroy
  • undefined method `on' for #<ActiveModel::Errors
Rails 4, the problem is that there's no "on" method for the Errors class anymore. We use "get". From

Change format something like that
@user.contact.errors.on(:attended_before)
 to
@user.contact.errors.get(:attended_before)
  • undefined method `call' when doing a simple query
Change scope from all models from

scope :enquiry, where({:involvement => INVOLVEMENT_ENQUIRY, :archived => false})
to
scope :enquiry, -> { where({:involvement => INVOLVEMENT_ENQUIRY, :archived => false}) }
  • Fix Typical Syntax on has_many like associations 
has_many :prices, -> { includes(:country).order("created_at desc") }, as: :priceable, dependent: :destroy, class_name: "Price"
  • Undefined method confirmed_me?
remove :confirmable from model where we have defined the devise parameters eg User model if not using
  • Unknown key: :include
Change has_many statement


  • NoMethodError (undefined method `authenticated?' )

FInd authenticated?  and replace with devise method valid_password?

  • NoMethodError (undefined method `forget_me' for
Copy forget_me method from restful-authentication to User model
  • link_to_function and the view helper with postfix _tag doesn’t work in rails 4 so the solution is
Add  Gem  into the gem file
gem 'prototype-rails'
In rails 2 prototype was supported but in rails 3 the jquery supports so we get the errors like
  • Keep in mind that the rails 2 already create a application.js and application.css in public folder so do not create same name files in assets folder. That can also give you conflicts.
  • element.dispatchEvent is not a function
Go to layout and check application layout


Here you have include the app/assets and public/assets together

So keep in mind the hierarchy of inclusion of files, in short
first jquery
second prototype
referred link
http://learn.jquery.com/using-jquery-core/avoid-conflicts-other-libraries/

<script src="prototype.js"></script>
<script src="jquery.js"></script>

After that include below in head of the html file the below line
<script>jQuery.noConflict();</script>
  • javascript_include_tag :default doesn’t work in rails 4
  • calendar_date_select doesn’t work in rails 4
  • LocalJump Error
This is due to the return keyword written in block. So remove return from the block.
  • undefined method `scoped' for
scoped method has been deprecated from rails 4. use all on place of it.
  • Search Or.. functionality was not working so change it that code
Replace div with some some id
  • Move all the assets from public folder to app folder



restful_authentication to Devise Migration


  • Add the following gem into your Gemfile
    • gem 'devise'
    • gem 'devise-encryptable'
  • Run the following commands from console
    • bundle intstall
    • rails g devise:install
  • In model file whatever you are using saving user information like user.rb
    • devise :database_authenticatable, :registerable, :recoverable, :rememberable, :confirmable, :validatable, :encryptable, :encryptor => :restful_authentication_sha1
          Modules :encryptable and :encryptor => :restful_authentication_sha1 are important here.
  • In config/initializers/devise.rb, configure as below
config.stretches = 1 config.pepper = ""

We are setting empty pepper and stretches to 1. This is how restful authentication works. It does not use stretches or pepper (by default).

( Note: You may find REST_AUTH_SITE_KEY in config/initializers/site_keys.rb )

In other case if You did set the REST_AUTH_SITE_KEY , then configure as below
config.stretches = 10
  config.pepper = "<YOUR_REST_AUTH_SITE_KEY>"

  • If you're using :validatable you may have to adjust your minimum password length. Devise uses 8, restful_authentication uses 6.
  • In config/initializers/devise.rb
                    config.password_length = 6..128

That is it for configuration. Now we have to change the table column names (without deleting them) to give devise what it wants. Here is the migration file I used. Change it according to your app's business logic.
  • Add migration to change columns
class ConvertRaToDevise < ActiveRecord::Migration
def self.up
  rename_column :users, "crypted_password", "encrypted_password"
 change_column :users, "encrypted_password", :string, :limit => 128, :default => "", :null => false
  rename_column :users, "salt", "password_salt"
  change_column :users, "password_salt", :string, :default => "", :null => false
  add_column :users, "remember_created_at", :datetime
end

def self.down
  remove_column :users, "remember_created_at"
  rename_column :users, "encrypted_password", "crypted_password"
  change_column :users, "crypted_password", :string, :limit => 40
  rename_column :users, "password_salt", "salt"
  change_column :users, "salt", :string, :limit => 40
end
end

You will able to use devise as authentication for your project.

Rails 2 to 4 UpGradation (Initial Level Settings)

Steps to upgrade the rails from 2 to 4 (Initial Level Settings)

  • Use latest ruby version first which is compatible with rails 4
  • Upgrade your Gems
    • Change versions for Gems into Gemfile .
    • Find alternative for gems which have been deprecated.
    • Comment some below gems if you have into you Gemfile
      • gem "mongrel"
      • gem "cgi_multipart_eof_fix" 
      • gem "fastercsv", '1.5.0'
      • gem “debugger"
    • Remove versions for these two basic Gems
      • gem 'mysql2'
      • gem 'rake'
  • Comment all the mime initializers in file config/initializers/mime_types.rb
  • Add config.egger_load in all rails environments in files config/environments/*
    • config.eager_load = true
  • Change match keyword from file routes.rb to get

You will able to run rails server from console

Wednesday, 30 September 2015

About Me

About Me

My name is Tarun Garg, I’m 25 year old Software Engineer.  As I spend my work days working with an organisation. I have 4 years of relative experience in rails I live in Delhi, India. My total experience includes website development in ruby on rails. I also like to work as a freelancer for extra pays. 
I have in-depth knowledge and experience in requirement gathering, analysis, design, development, testing, API designs, AWS technologies and implementation of methodologies. I also offers experience in preparing standard documents such as program specification, design document, and training document. I am proficient in understanding business processes and requirements, and translating them into functional specifications. I have ability to build world class products using Agile/Scrum.
My responsibilities as Software developer includes client handling, better code optimizations, client satisfactions, understand requirements, better listener and give best to client. I assisted in the successful completion of some projects based on ROR. My clients also relied on my ability to skills such as code optimization, task completion, meet client requirements and excellent communications skills.