Showing posts with label Ruby. Show all posts
Showing posts with label Ruby. Show all posts

Friday, March 16, 2018

How to install rbenv and Ruby build


rbenv use to setup different ruby environment based on your application, it's a nifty tool for development environment especially if your working different Ruby applications.


Installing instruction for rbenv
$ brew install rbenv
Add rbenv's bin path into .rc(.bash_profile) file
export PATH="$HOME/.rbenv/bin:$PATH" 
if which rbenv > /dev/null; then eval "$(rbenv init -)"; fi
Make sure you have reloaded terminal with env changes

Installing specific Ruby version Ex. 2.3.4
$ rbenv install 2.3.4

ruby-build: use openssl from homebrew
Downloading ruby-2.3.4.tar.bz2...
-> https://cache.ruby-lang.org/pub/ruby/2.4/ruby-2.3.4.tar.bz2


Installing ruby-2.3.4...


Installed ruby-2.3.4 to /Users/home/.rbenv/versions/2.3.4

Make your Ruby 2.3.4 as global 
$ rbenv global 2.3.4
$ ruby -v
ruby 2.3.4p301 (2017-03-30 revision 58214) [x86_64-darwin17]
Sets the global version of Ruby to be used in all shells by writing the version name to the ~/.rbenv/version file. This version can be overridden by an application-specific .ruby-version file, or by setting the RBENV_VERSION environment variable.

Monday, February 26, 2018

Design Patterns - Singleton

Singleton pattern is frequently used to provide global access point for a service. It restricts instantiation of a class to only one instance that globally available.

It's useful in your application when you need global instance which can be accessible in different parts of the application. Most common use case of this pattern is Application logging and configuration functionality.

Singleton pattern in Ruby

Class Logger
def initialize
@log = File.open("/tmp/tmp.log", "a")
end

@@instance = Logger.new

def self.instance
@@instance
end

def log(message)
@log.puts(message)
end

private_method :new
end


Logger.instance.log("Log me")

In this example, we created an instance of the "Class Logger" which can be accessed by class method "Logger.instance", so when you want to log any errors/warning/notice on your app, you can simply use "log" instance method which just opened a log file and appending message on that file. 

 At the end of the class we made method "new" as private, so that anywhere in the application we can't create new instance of Class "Logger"

Friday, January 19, 2018

Ruby - Array#bsearch

Array bsearch it's very handy and one of the fastest way to find a value from the array.

Let's do benchmark analysis, based on the result, bsearch more powerful than using array find method. 
require 'benchmark'

array_data = (0..100_000_000)

Benchmark.bm do |x|
x.report(:find) { array_data.find {|number| number > 50_000_000 } }
x.report(:bsearch) { array_data.bsearch {|number| number > 50_000_000 } }
end

user system total real
find 3.160000 0.000000 3.160000 ( 3.174570)
bsearch 0.000000 0.000000 0.000000 ( 0.000011)

It can find a match with only O(log n) complexity. 

Wednesday, August 21, 2013

Rails 4 - Scope

In rails 4, scopes should take a proc object or a block. Take an example this User model
Class User < ActiveRecord::Base
  attr_accessor :name,:age,:status

  def initialize(name, age)
    @name = name
    @age = age
  end
end
I would like to make default scope based on status 'user' and admin scope based on status 'admin'. In rails 3, I can make scope like this
#Rails 3
scope :admin, where(status: 'admin')
default_scope where(status: 'user')

Rails 4, I can make scope this way
#Rails 4
default_scope { where(status: 'user') } #  block
#default_scope ->{ where(status: 'admin) } #Proc valid
scope :admin, ->{ where(status: 'admin') }
If we try to use scope without(see rails3 examples) passing proc or block in Rails 4, it triggers DEPRECATION WARNING message.

Rails 4 - Finders

Old-Style finders are deprecated
In Rails 4, Old-Style finders are deprecated. Consider User model with name, age members
Class User < ActiveRecord::Base
  attr_accessor :name,:age

  def initialize(name, age)
    @name = name
    @age = age
  end
end

In this class, If we want find user with name of 'foo'. See the difference in rails 3 and rails 4 call
#Rails 3
User.find(:all, conditions: { name: 'foo' })
#Rails 4
User.where(name: 'foo')

In rails 4, you will get DEPRECATION WARNING: Calling #find(:all) is deprecated. You can call #all directly instead or build a scope instead of using finder options.

Dynamic finders that return collections are deprecated
#Rails 3
User.find_all_by_name('foo')
#Rails 4
User.where(name: 'foo')

In Rails 4 alerts DEPRECATION WARNING if we use dynamic method(User.find_all_by_name). Preferable alternative option is User.where(...).all

Thursday, September 6, 2012

Install Postgres gem issue on rails app

When you try to install postgres gem for your application, but unfortunately you end up with this problem

$ gem install pg -v '0.14.0'

Building native extensions.  This could take a while...
ERROR:  Error installing pg:
    ERROR: Failed to build gem native extension.

        /home/user/.rvm/rubies/ruby-1.9.3/bin/ruby 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... *** 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
    --without-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.3/bin/ruby
    --with-pg
    --without-pg
    --with-pg-dir
    --without-pg-dir
    --with-pg-include
    --without-pg-include=${pg-dir}/include
    --with-pg-lib
    --without-pg-lib=${pg-dir}/lib
    --with-pg-config
    --without-pg-config
    --with-pg_config
    --without-pg_config

Solution:

$ sudo apt-get install libpq-dev

You need to install postgresql-server for building a server-side extension or libpq-dev for building a client-side application.


Monday, September 3, 2012

Could not find a JavaScript runtime. See https://github.com/sstephenson/execjs for a list of available runtimes. (ExecJS::RuntimeUnavailable)

$ rails server

/home/user/.rvm/gems/ruby-1.9.3-p194/gems/execjs-1.4.0/lib/execjs/runtimes.rb:51:in `autodetect': Could not find a JavaScript runtime. See https://github.com/sstephenson/execjs for a list of available runtimes. (ExecJS::RuntimeUnavailable)
             from /home/user/.rvm/gems/ruby-1.9.3-p194/gems/execjs-1.4.0/lib/execjs.rb:5:in `<module:ExecJS>'
 
The reason for this issue is missing Node JS Package Manager. Check this link for how to install package manger based on your operating system.

https://github.com/joyent/node/wiki/Installing-Node.js-via-package-manager

I hope it may help you to solve the problem.

The program 'rails' is currently not installed. You can install it by typing: sudo apt-get install rails

user@localhost:~$ rails new blog
The program 'rails' is currently not installed.  You can install it by typing: sudo apt-get install rails

If you get this message when you were creating new rails project. To fix this issue

1. Go to profile settings (.bashrc or .bash_profile)

2. Add this line at end of the file

[[ -s "$HOME/.rvm/scripts/rvm" ]] && source "$HOME/.rvm/scripts/rvm" # Loading RVM into a shell

3. If you are in existing shell prompt, execute this command

source ~/.bashrc
or
source ~/.bash_profile

If you open a new terminal, you can notice  that rails command is automatically available.I hope this post helpful to fix rails command issue.



Note:
I believe you have installed ruby by Ruby Version Manger(RVM). Refer the installation steps
https://rvm.io/rvm/install/


Monday, July 30, 2012

Rails 3 - Bundler

Bundler

Bundler is used to manage your application's gem dependencies. By default all Rails 3 application contains bundler gem.

If your applications need gems other than those belonging to Rails itself, you'll need to specify those gems into manifest file named Gemfile into the root of your Rails project directory.

Simple syntax to load gem

gem "paperclip"
gem "rspec"

Syntax to load gem on specific application environment

group :development, :test do
   gem "rspec"
end

Syntax to load specific gem version

gem "rspec" , "1.2"
gem "rspec", "> 1.2"

Syntax to load gem form a Git Repository

gem "paperclip", :git => "git://github.com/thoughtbot/paperclip.git"

Installing Gems

Once you update the Gemfile then make sure you have installed all the dependencies in your Gemfile of Rails 3 applications.

$ bundle install
$ bundle install --without test

These commands will install all gem dependencies on your Rails 3 application which is specified on Gemfile.

Packing Gems

You can package up all your gems in the vendor/cache directory inside of your Rails 3 applications.

Here is the syntax to package up

$ bundle package

I hope you have some idea about Bundler and how it helpful in Rails 3 applications. If you need any clarifications please let me know.

Friday, July 27, 2012

Rails 3.2.7!

Rails Team has been announced version 3.2.7. It contains important security fixes(see here), so update quickly.

Source code & change logs are available here
https://github.com/rails/rails/compare/v3.2.6...v3.2.7

Reference:
http://rubyonrails.org/

Saturday, June 23, 2012

Rails 3 tips - Create project with different database(MySQL,PostGresSQL,JDBC,SQL SERVER, etc)

Here are commands to create Rails 3 application with different database

MySQL
rails new app --database=mysql

ORACLE
rails new app --database=oracle

PostgreSQL
rails new app --database=postgresql

SQLite3
rails new app --database=sqlite3

FrontBase
rails new app --database=frontbase

IBM DB
rails new app --database=ibm_db

SQL SERVER
rails new app --database=sqlserver

JDBC
rails new app --database=jdbc

JDBC MySQL
rails new app --database=jdbcmysql

JDBC PostgreSQL
rails new app --database=jdbcpostgresql

JDBC SQLite3
rails new app --database=jdbcsqlite3

Friday, May 25, 2012

Ruby 1.9.3 - defined?

defined?
It's a ruby method for checking passed expression defined or not

Some examples

1.9.3p0 :025 > message = "hello" => "hello" 1.9.3p0 :031 > defined? message => "local-variable" 1.9.3p0 :032 > if defined? message 1.9.3p0 :033?> puts "message defined" 1.9.3p0 :034?> end message defined
1.9.3p0 :050 > defined? $_ => "global-variable"

1.9.3p0 :052 > defined? lastname => nil

1.9.3p0 :053 > books = [] => [] 1.9.3p0 :054 > defined? books => "local-variable"

1.9.3p0 :055 > name = "" => "" 1.9.3p0 :056 > defined? name => "local-variable" 1.9.3p0 :057 > author = "Steve" => "Steve" 1.9.3p0 :058 > defined? author => "local-variable" 1.9.3p0 :059 > object = String.new => "" 1.9.3p0 :060 > defined? object => "local-variable"

I hope you understand defined? method from these examples.

Tuesday, May 22, 2012

Procs in rails 3

Proc is an object of code blocks that are assigned into variable.Proc and Blocks are same, but the primary difference is performance.

def say_message_with_name(message) Proc.new do |name| message + " " +name end end
message1 = say_message_with_name("Good morning") message1.call("Tom")
In this example, simply show message with name. Proc is created when constructor is called and given a block as a parameter

The code in the block is treated as Proc instance and can be called any time.You can call Proc code block anytime using "call" method

Output of above example

1.9.3p0 :011 > def say_message_with_name(message) 1.9.3p0 :012?> Proc.new do 1.9.3p0 :013 > |name| message + " " +name 1.9.3p0 :014?> end 1.9.3p0 :015?> end => nil
1.9.3p0 :016 > message1 = say_message_with_name("Good morning") => #<Proc:0x8e8382c@(irb):12> 1.9.3p0 :017 > message1.call("Tom") => "Good morning Tom"

Purpose of Proc

If you want to create a block of code and pass it around on you're application or generate new blocks from existing block.

Blocks in rails 3

Blocks are generally simple code wrapped in a do/end construct.

Example

books = %w{book1 book2 book3 book4}
books.each do |name| print "Book name :: #{name}\n" end

In this example code between do and end is Blocks. what it does is that iterates an array using the each method and passes in each element(i.e name) to the code block

Monday, May 21, 2012

Ruby method calling

Different way of Ruby method calling

puts "Hello world"
puts ("Hello world")
puts
puts()

Above type applies only ruby puts method. it may vary for other methods based on definition

Ruby method - 1.9.3

Simple ruby method definition

1.9.3p0 :016 > def my_method(message)
puts "Hello," + message
end

Method call

1.9.3p0 :016 > my_method("World")
=> Hello, World

Ruby method with variable length parameters

1.9.3p0 :016 > def author_books(author, *books)
puts "Author #{author} is written books - #{books.join(', ')}"
end

Method call

1.9.3p0 :016 >author_books("x-author","book1","book2","book3")
=> Author x-author is written books - book1,book2,book3

Sunday, May 20, 2012

Rails 3 - Routing

Purpose of rails router is that understanding requesting URLs and dispatches them to a controller's action.

Rails 3 introduced new routing DSL which is slight different than rails 2

Examples:

1. Simple route to welcome page which is handled by index action in shops controller

# Rails 2
map.connect 'welcome', :controller => 'shops', :action => 'index'

# Rails 3
match 'welcome' => 'shops#index'

2. Resources - which allows us to quickly declare all of the common routes for a given resourceful controller

# Rails 2

map.resources :products

# Rails 3

resources :products
It creates different routes in your application for Products controller. The routes are /products,/products/new,/products/:id,/products/:id/edit,etc.

3. Namespaces and Routing

Suppose if you want to organize group of controller under a namespace, Example scenario would be mapping admin specific controllers under admin namespace.

# Rails 2

map.namespace :admin do |admin|
  admin.resources :controller => 'orders'
end

# Rails 3
namespace :admin do
  resources :orders
end

In this case you can access admin specific controllers by /admin/orders, etc

4. Simple ROOT mapping on rails 2 and rails 3

# Rails 2

map.root :controller => 'stores', :action => 'index'

# Rails 3

root :to => 'stores#index'

Stores's index action will be called if you access web application directly - http://example.com

Thursday, May 10, 2012

JRuby 1.6.7.2 Released!

The JRuby community announced the release of JRuby 1.6.7.2.
It's shipped copy of RubyGems to version 1.8.24.This version of RubyGems is the first version to verify that a RubyGems server certficate is valid. This helps to prevent a “man in the middle” style of attack when someone controls a portion of the network between you and the RubyGems server
Download:

http://www.jruby.org/download

References
http://jruby.org

Wednesday, May 9, 2012

Ruby/Rails 3 with NetBeans IDE 7.1.2


This post help you to install Rails 3/Ruby Plugin for NetBean IDE 7.1.2.
Nice Stuff i noticed after install this plugin
1. Open you're existing rails 3 project
2. Open new rails 3 project
3. Run/Debug Rake Task
4. Ruby Shell
5. Rails Console
6. Migrate database
7. Run
8. Debug,etc

I hope it makes rails development faster.

Monday, May 7, 2012

Install & setup Passenger module on Apache2 - Ubuntu 11.10

This guide help you to deploy Rails 3 application on apache2.

1. Install passenger gem on you're machine
$ sudo gem install passenger

2. Install apache2 module for passenger
$ sudo passenger-install-apache2-module

It does following three steps

a. The Apache 2 module will be installed for you.

If any software not available on you're server to install apache 2 module. It will guide you about missing software and some suggestion how to install those missed software

Once all support software available, then it compile & install apache 2 module.

b. Guide you how to configure apache

Once apache2 module installed, it guide you to configure apache - display LoadModule, RailsSpawnServer and RailsRuby location which will be required to configure passenger module on apache(httpd.conf).Just copy and paste those lines to httpd.conf

c. Guide you how to deploy a Ruby on Rails application
<VirtualHost *:80>

ServerName www.yourhost.com

DocumentRoot /somewhere/public

</VirtualHost>

add this virtualhost configuration on httpd.conf file

Now i hope you're apache2 server ready to deploy rails 3 application. it use passenger module for apache2.