current_page?


Sometimes we come to scenario, we need to find out what the current page is. The best I could do was this:

1. current_page?(options)

Will return true if the current request URI was generated by the given options.
Let’s say we’re in the /shop/checkout?order=desc action.
current_page?(:action => ‘process’)
# => false

current_page?(:controller => ‘shop’, :action => ‘checkout’)
# => true

2. request.path_parameters

this should return a hash along the controller and action.
{:action => ‘my_action’, :controller => ‘my_controller’}

Thanks

Ruby Basic sales tax problem


Q. Basic sales tax is applicable at a rate of 10% on all goods, except books, food, and medical products that are exempt.
Import duty is an additional sales tax applicable on all imported goods at a rate of 5%, with no exemptions.

When I purchase items I receive a receipt which lists the name of all the items and their price (including tax),
finishing with the total cost of the items, and the total amounts of sales taxes paid.

The rounding rules for sales tax are that for a tax rate of n%, a shelf price of p contains (np/100 rounded up to the
nearest 0.05) amount of sales tax.

Write an application that prints out the receipt details for these shopping baskets…

INPUT:

Input 1:
1 book at 12.49
1 music CD at 14.99
1 chocolate bar at 0.85

Input 2:
1 imported box of chocolates at 10.00
1 imported bottle of perfume at 47.50

Input 3:
1 imported bottle of perfume at 27.99
1 bottle of perfume at 18.99
1 packet of headache pills at 9.75
1 box of imported chocolates at 11.25

OUTPUT

Output 1:
1 book : 12.49
1 music CD: 16.49
1 chocolate bar: 0.85
Sales Taxes: 1.50
Total: 29.83

Output 2:
1 imported box of chocolates: 10.50
1 imported bottle of perfume: 54.65
Sales Taxes: 7.65
Total: 65.15

Output 3:
1 imported bottle of perfume: 32.19
1 bottle of perfume: 20.89
1 packet of headache pills: 9.75
1 imported box of chocolates: 11.85
Sales Taxes: 6.70
Total: 74.68

Code

class SalesTexes
 
  RECEIPT1 = [“1 imported box of chocolates at 10.00”, “1 imported bottle of perfume at 47.50”]
  RECEIPT2 = [ “1 book at 12.49”, “1 music CD at 14.99”, “1 chocolate bar at 0.85” ]
  RECEIPT3 = [ “1 imported bottle of perfume at 27.99”, “1 bottle of perfume at 18.99”, “1 packet of headache pills at 9.75”, “1 box of imported chocolates at 11.25”]
 
  TAX_EXCEPT_ITEM = [“chocolates”,”book”,”pills”,”chocolate”]
 
  IMPORT_TAX = 0.05
  SALES_TAX = 0.10
  BOTH_TAX = 0.15
  CENTS_ROUNDING_MULTIPLIER = 20.0
 
  def initialize
    puts “*************First receipt*****************”
    get_input RECEIPT1
    puts “*************Second receipt*****************”
    get_input RECEIPT2
    puts “*************Third receipt*****************”
    get_input RECEIPT3
  end
 
  def get_input input_array
    total_tax = 0
    total_price = 0
    input_array.each do |each_item|
       i_item = each_item.split
       qty = i_item[0].to_i
       price = i_item[-1].to_f
       p = each_item.split(” at “)
       product = p[0].delete(“/0-9/”).strip
       tax = tax_cal price,product
       total_tax += tax
       tax_price = (price.to_f + tax)
       total_price += tax_price
       p “#{qty} #{product}: #{tax_price.round(2)}”
    end
    p “Sales Tax: #{total_tax.round(2)}”
    p “Total: #{total_price.round(2)}”
  end
 
  def tax_cal price,product
    tax_exclude = []
    a_product = product.split(” “)
    tax_exclude = a_product & TAX_EXCEPT_ITEM
    if product.include?(‘imported’) and tax_exclude.count != 1
      tax = price.to_f * BOTH_TAX
    elsif product.include?(‘imported’) and tax_exclude.count == 1
      tax = price.to_f * IMPORT_TAX
    elsif tax_exclude.count != 1
      tax = price.to_f * SALES_TAX
    else
      tax = 0
    end
    return tax
  end
 
end

SalesTexes.new
 

 

 

ruby script for reading the contents of a file and appending in othere file


Content of text file
readdata.txt

Hi, This is Pravin Mishra
Ruby on rails developer
From India

and generating some output based on the content:

readfile.rb


class ReadFile
 
  def execute
    file = File.open(“readdata.txt”)
    contents = []
    all_data = Hash.new
    file.each {|line|
        tokens = line.split(” “)
       
        if tokens.count > 1
            tokens.each_with_index do |data, index|
              all_data[index] = data
            end
            contents << all_data
            all_data = Hash.new
        end
        
        my_file = File.new(“new_file.txt”, “w”)
        my_file.puts contents
    }

  end
 
end

if __FILE__ == $0
  sql = ReadFile.new
  sql.execute
end

Run from the command line as:

> ruby readfile.rb

Out put would be
{0=>”Hi,”, 1=>”This”, 2=>”is”, 3=>”Pravin”, 4=>”Mishra”}
{0=>”Ruby”, 1=>”on”, 2=>”rails”, 3=>”developer”}
{0=>”From”, 1=>”India”}
in new_file.txt

that’s it…!!!

Truncate string with Ruby/Rails


Ruby:-

1.9.3p125 :079 >   list = “Hi, this is Ruby on rails developer”
=> “Hi, this is Ruby on rails developer”
1.9.3p125 :080 > list.truncate(10)
=> “Hi, thi…”
1.9.3p125 :081 > list.truncate(20)
=> “Hi, this is Ruby …”
1.9.3p125 :083 > list[0..10]
=> “Hi, this is”
1.9.3p125 :084 > list[0..20]
=> “Hi, this is Ruby on r”

1.9.3p125 :108 >   list.slice(0 , 10)
=> “Hi, this i”

Rails:-

– @organization_applied_name.each do |each_org_name|
%li
= link_to “#{truncate(each_org_name, :length => 25)}”, “#”
= link_to “#{each_org_name[0..10]}”, “#”

 

Ruby Array


Basics of ruby Array.

1.How to create ruby array

1.9.2p318 :002 > order = [“Book”,”Pen”,”Computer”,”Bus”]

=> [“Book”, “Pen”, “Computer”, “Bus”]

1.9.2p318 :002 > list = %(car moter rails ruby)

=> “car moter rails ruby”

1.9.2p318 :003 > name = Array.new

=> []

1.9.2p318 :004 > name << ‘Pravin’

=> [“Pravin”]

1.9.2p318 :005 > name << ‘Ankit’

=> [“Pravin”, “Ankit”]

1.9.2p318 :006 > name << ‘Abhay’

=> [“Pravin”, “Ankit”, “Abhay”]

1.9.2p318 :007 > name << ‘Abinaw’

=> [“Pravin”, “Ankit”, “Abhay”, “Abinaw”]

2. collect and map

Invokes block once for each element of self. Creates a new array containing the values returned by the block

1.9.2p318 :030 > order.collect{|item| item}

=> [“Book”, “Pen”, “Computer”, “Bus”]

1.9.2p318 :031 > order.collect{|item| item+”1″}

=> [“Book1”, “Pen1”, “Computer1”, “Bus1”]

1.9.2p318 :032 > order

=> [“Book”, “Pen”, “Computer”, “Bus”]

1.9.2p318 :033 > order.map{|item| item+”1″}

=> [“Book1”, “Pen1”, “Computer1”, “Bus1”]

1.9.2p318 :034 > order

=> [“Book”, “Pen”, “Computer”, “Bus”]

3. collect! And map!

Invokes the block once for each element of self, replacing the element with the value returned by block

1.9.2p318 :035 > order.map!{|item| item+”1″}

=> [“Book1”, “Pen1”, “Computer1”, “Bus1”]

1.9.2p318 :036 > order

=> [“Book1”, “Pen1”, “Computer1”, “Bus1”]

1.9.2p318 :037 > order.collect!{|item| item+”2″}

=> [“Book12”, “Pen12”, “Computer12”, “Bus12”]

1.9.2p318 :038 > order

=> [“Book12”, “Pen12”, “Computer12”, “Bus12”]

4.compact

Returns a copy of self with all nil elements removed.

1.9.2p318 :050 > order

=> [“Book12”, “Pen12”, “Computer12”, “Bus12”]

push a nil element to array

1.9.2p318 :059 > order << nil

=> [“Book12”, “Pen12”, “Computer12”, “Bus12”, nil]

1.9.2p318 :060 > order.compact

=> [“Book12”, “Pen12”, “Computer12”, “Bus12”, “”, “”, “nil”]

5.compact!

Removes nil elements from array. Returns nil if no changes were made.

1.9.2p318 :062 > order << nil

=> [“Book12”, “Pen12”, “Computer12”, “Bus12”, nil]

1.9.2p318 :063 > order.compact!

=> [“Book12”, “Pen12”, “Computer12”, “Bus12”]

1.9.2p318 :064 > order.compact!

=> nil

6.delete_if

Deletes every element of self for which block evaluates to true.

1.9.2p318 :088 > number_list = [‘2′,’8′,’4′,’3′,’9’]

=> [“2”, “8”, “4”, “3”, “9”]

1.9.2p318 :089 > number_list.delete_if{|item| item >= ‘4’}

=> [“2”, “3”]

7.empty?

Returns true if self array contains no elements.

1.9.2p318 :090 > number_list

=> [“2”, “3”]

1.9.2p318 :091 > number_list.empty?

=> false

1.9.2p318 :092 > number_list.delete_if{|item| item > ‘0’}

=> []

1.9.2p318 :093 > number_list

=> []

1.9.2p318 :094 > number_list.empty?

=> true

8.eql?

Returns true if array and other are the same object, or are both arrays with the same content.

1.9.2p318 :097 > number_list << ‘4’

=> [“4”]

1.9.2p318 :098 > number_list << 8

=> [“4”, 8]

1.9.2p318 :099 > number_list << “test”

=> [“4”, 8, “test”]

1.9.2p318 :101 > number_list1 = Array.new

=> []

1.9.2p318 :102 > number_list1 << “test”

=> [“test”]

1.9.2p318 :103 > number_list1 << 5

=> [“test”, 5]

1.9.2p318 :104 > number_list1.eql?(number_list)

=> false

1.9.2p318 :105 > number_list1

=> [“test”, 5]

1.9.2p318 :106 > number_list1.delete_at(1)

=> 5

1.9.2p318 :107 > number_list1

=> [“test”]

1.9.2p318 :108 > number_list

=> [“4”, 8, “test”]

1.9.2p318 :109 > number_list.delete_at(1)

=> 8

1.9.2p318 :110 > number_list.delete_at(0)

=> “4”

1.9.2p318 :111 > number_list

=> [“test”]

1.9.2p318 :112 > number_list1.eql?(number_list)

=> true

9.include?

Returns true if the given object is present in self (that is, if any object == anObject), false otherwise.

1.9.2p318 :124 > number_list

=> [“test”]

1.9.2p318 :125 > number_list.push(5)

=> [“test”, 5]

1.9.2p318 :126 > number_list.push(“apple”)

=> [“test”, 5, “apple”]

1.9.2p318 :127 > number_list.include?(5)

=> true

1.9.2p318 :128 > number_list.include?(‘5’)

=> false

1.9.2p318 :129 > number_list.include?(‘apple’)

=> true

1.9.2p318 :130 > number_list.include?(‘apple1’)

=> false

10.index(obj)

Returns the index of the first object in self such that is == to obj. Returns nil if no match is found.

1.9.2p318 :141 > number_list

=> [“test”, 5, “apple”]

1.9.2p318 :142 > number_list.index(5)

=> 1

1.9.2p318 :143 > number_list.index(‘test’)

=> 0

1.9.2p318 :144 > number_list.index(’empty’)

=> nil

11.join

Returns a string created by converting each element of the array to a string, separated by sep.

1.9.2p318 :155 > number_list

=> [“test”, 5, “apple”]

1.9.2p318 :157 > number_list.join(‘-‘)

=> “test-5-apple”

12.nitems

Returns the number of non-nil elements in self. May be zero.

13. slice!

Deletes the element(s) given by an index (optionally with a length) or by a range. Returns the deleted object, subarray, or nil if the index is out of range. Equivalent to:

1.9.2p318 :220 > number_list

=> [“test”, 5, “dog”]

1.9.2p318 :221 > number_list.slice!(2)

=> “dog”

1.9.2p318 :222 > number_list

=> [“test”, 5]

1.9.2p318 :223 > number_list.slice!(2)

=> nil

1.9.2p318 :224 > number_list

=> [“test”, 5]

1.9.2p318 :225 > number_list.slice!(0)

=> “test”

1.9.2p318 :226 > number_list

=> [5]

14.sort

Returns a new array created by sorting self. Comparisons for the sort will be done using the <=> operator or using an optional code block. The block implements a comparison between a and b, returning -1, 0, or +1.

1.9.2p318 :229 > number = [‘2′,’9′,’7′,’4’]

=> [“2”, “9”, “7”, “4”]

1.9.2p318 :230 > number.sort{|a,b| a <=> b}

=> [“2”, “4”, “7”, “9”]

Procs and Lambdas


There are two main differences between lambdas and  Procs:

1. Lambdas and procs both are the methods, But with bit difference. Procs return whole methods where as Lambdas return from themselves.

     2. One other major difference is that,lambdas have strict argument checking, whereas Procs have loose argument checking

Trim white spaces from ruby string


Let’s play with ruby function to remove all white spaces.
1.9.3p125 :001 > a = “Miasa Pride”
 => “Miasa Pride”
1.9.3p125 :002 > a.strip
 => “Miasa Pride”
1.9.3p125 :006 > a.gsub(/\s+/, “”)
 => “MiasaPride”
1.9.3p125 :007 > b = ” Miasa Pride “
 => ” Miasa Pride “
1.9.3p125 :008 > b.gsub(/\s+/, “”)
 => “MiasaPride”
1.9.3p125 :009 > c = ” Miasa@Pride “
 => ” Miasa@Pride “
1.9.3p125 :010 > c.gsub(/\s+/, “”)
 => “Miasa@Pride”
Cheers….!!!!!!!!

 

Export data to CSV and Excel in your Rails


A common requirement from customers is the ability to export tabular data to a CSV file that can be imported into Excel. Ruby on Rails uses the standard ruby CSV library to import test fixtures that are in CSV format.

Below are the steps we need to follow.

1. require the CSV library to controller, Where we need to write import code

require 'csv'

2. Emport code in controller

def export_to_csv       
    @users = User.find(:all)
    csv_string = CSV.generate do |csv|
         csv << ["Id", "Name", "Email","Role"]
         @users.each do |user|
           csv << [user.id, user.name, user.name, user.role]
         end
    end         
  
   send_data csv_string,
   :type => 'text/csv; charset=iso-8859-1; header=present',
   :disposition => "attachment; filename=users.csv" 
end 


@users = User.find(:all)
Fetching all user details and assigned on @users
csv_string = CSV.generate do |csv|
Using CSV class generate method to create csv file
csv << ["Id", "Name", "Email","Role"] 
Creating header of CSV file

@users.each do |user|
  csv << [user.id, user.name, user.name, user.role] 
end 
Retrieving each rows and assigning on csv_string variable.


send_data csv_string,
:type => 'text/csv; charset=iso-8859-1; header=present',
:disposition => "attachment; 
filename=users.csv" 
sending data to browser. 

Enjoy...........