Posts tagged ‘RoR’
Generate Unique ID
Here is a very simple way to generate a unique id.
[Background support : Abhishek S.]
def generate_unique_id( len )
chars_pattern = ("a".."z").to_a + ("A".."Z").to_a + ("0".."9").to_a
unique_id = ""
1.upto(len) {
|i| unique_id << chars_pattern[rand(chars_pattern.size-1)] }
return unique_id
end
#generates a key of length 10
mykey = generate_unique_id(10)
print mykey # gives a result like "qeKX0myIQh"
render in rails
What do you see in a browser is nothing but a response; which is a combination of header and some document data.
From where does it come? -> Through the action of some controller.
Each action results in a response,
response = headers + document content
This resonse object is generated using various types of renders/redirects. Action Controller sends content to the user by using these rendering methods.
By default, actions are rendered within the current layout (if one exists)
- AUTOMATIC RENDER
def myname
@name = “rajesh”
end
myname.rhtml ->My name is “#{@name}”
Yes this is also a type of render; an automatic rendering using instance var.
- SIMPLE RENDER
def method1
@val = 30
render :action => “method2″, :layout => “mylayout1″
return
end
> This will execute the view of method2,
> Nothing will appear as a view for method1
> there is no relation what all defined in action def method2
> Any instance var defined before this statment can be executed in the view for method2 (not in action)
means in readered view of method2.rhtml
puts @val # returns you 30
where as
def method2
puts @val # dont expecct 30 in direct way
end
> TWO render is not possible in same action, else gives error, coz control exececutes code after the render statement.
- RENDER PARTIAL
def method1
@val = 30
render :partial => “my_first_partial”
return
end
> render partial can be used in both controller as well as view, while plain render can be used in controller only
> In controller if you are using -> render :partial => “my_first_partial”
Layout will be lost of the current method i.e method1; But if you want to preserve it use layout as true
render :partial => “my_first_partial”, :layout => ‘true’
> If you are using it in view then layout of method1 will be preserved.
> instance var is well accessible in partial file, but if you want to pass the local var, then must use locals
render :partial => “my_first_partial” , :locals => {:q => 90}
- RENDERING TEXT
render :text => “hello”, :layout => true
render :inline => “<%= ‘hello, ‘ * 3 + ‘again’ %>”, :layout => true
- REDIRECTS_TO
redirect_to refers the method while render seeks you to the corresponding view.
You cant have these two together without any conditional statment.
RENDER -> populates a VIEW
REDIRECT -> hammers an ACTION
[Background support : Himanshu P.]
Sorting an Array of hashes
We get a situation where we fetch some set of records from db as an array of hashes, and later we need to sort this array based on some field of DB.
Here is a very hand code to do so.
array_objs =[ {:title => "row1_title" ,:name => "Mumbai"},
{:title => "row2_title" ,:name => "Delhi"},
{:title => "row3_title" ,:name => "Bangalore"} ]
array_objs .sort_by {|array_objs| array_objs [:name] }.each do |res|
puts "#{res[:name] }"
end
O/P:
Bangalore
Delhi
Mumbai
do while in ruby
How to achieve the do ..while loop in Ruby?
Yes this can be, just bit tricky.
Just consider one of the syntax of while loop in ruby
<expression> while <expression>
This repeats evaluation of left hand side expression, while right hand side is true.
x = 5 begin print x print " " x += 1 end while(x<10) o/p 5 6 7 8 9
blank,empty and nil in Ruby
Object.blank?
Returns true if:
> it’s an empty array
> it’s an empty string
> !self evaluates to true
[].blank? #=> true
[1].blank? #=> false
[nil].blank? #=> false
nil.blank? #=> true
true.blank? #=> false
false.blank? #=> true
"".blank? #=> true
" ".blank? #=> true
" i ".blank? #=> false
String.empty?
"hello".empty? #=> false
"".empty? #=> true
Array.empty?
[].empty? #=> true
Hash.empty?
{}.empty? #=> true
NilClass.nil?
nil.nil? => true
Object.nil?
nil.nil? => true
.nil? => false
nil.inspect ? "nil"
find(ActiveRecord::Base)
# returns the object for very first row or dierctly put the first row ID like 156789
find_first_as_object = Rating.find(:first)
#p find_first_as_object.ratee_identity_id #1287065605
find_first_as_object_using_idnum = Rating.find(1) # search for id =1
# returns as an array of object(one element array)
find_first_as_array = Rating.find([569384240])
# p find_first_as_array[0].ratee_identity_id #1287065605
find_first_with_condition = Rating.find(:first, :conditions => [”rating = 4?])
==================================
find_objects_with_selected_attributes = Rating.find(:all,:select => ‘rating as RR’)
my_distinct = Rating.find(:all, :select =>”distinct rating” )
find_first_with_condition_plus_order = Rating.find(:first,
:conditions => [”rating = 4?],
:order => “ratingdate DESC”)
===================================
find_all = Rating.find(:all) # returns an array of objects
find_all_by_limit = Rating.find(:all, :conditions => [”rating >= 3 “],:limit => 10)
find_all_by_group = Rating.find(:all,
:conditions => [”rating >= 3 “],
:group => “rating”)
===================================
# find_by_sql returns an ARRAY of objects
find_sql = Rating.find_by_sql(”select rating as goodRating from ratings where rating >=3?)
find_sql_using_var = Rating.find_by_sql(”select * from ratings where id = ?”, ratee_identity_id)
===================================
find_first_by_rating = Rating.find_by_rating(”3?)
# Rating.find(:first, conditions => “rating = 3”)
find_all_by_rating = Rating.find_all_by_rating(”3?)
# Rating.find(:all, conditions => “rating = 3”)


