Posts Tagged Ruby

“The ruby-debug Commands”


The ruby-debug Commands

What follows is a quick rundown of the most important ruby-debug commands, along with a brief description of what they do. Don’t worry too much about remembering every last detail — the built-in help command will list all the available commands for you. You can also use the help <commandname> syntax to get help with a specific command.

  • backtrace: Display a trace of the execution stack, similar to what is displayed when your application raises an exception.
  • break/delete: Display a list of breakpoints that have been set in your application. This command is also used to set new breakpoints, or delete existing ones, from within the ruby-debug shell.
  • cont: Leave the current debugger shell and resume execution of the application until the next breakpoint is encountered.
  • irb: Invoke an interactive Ruby interpreter at the current point of execution, similar to the shell used by the breakpoint library.
  • list: Display the code fragments surrounding the current point of execution. (We’ll make use of this command in a moment.)
  • method/method instance: Explore the available class methods and instance methods, respectively.
  • next/step: Continue execution one step at a time — this is a huge improvement over the breakpoint library.
  • p/pp: Short for print and pretty print respectively, these commands can be used to evaluate Ruby expressions and display the value of variables to the console.
  • quit: Exit the debugger. Note that this will also exit the application server if it was invoked from the command line, as demonstrated above. To just exit the current debugging session, use cont.
  • reload: Reload the Ruby source files from disk. This can be useful if you’ve changed class definitions and want to reload them dynamically without leaving the current debugging session.

For a list of all available commands and options, use the help command.

, , ,

Add comment November 12, 2008

“Debugging in rails”

Well ever thought of debugging the rails application , there are many ways , one way which I liked of lately was the debugger in action directly.

Step 1 :  Install ruby-debugger gem “sudo gem install ruby-debugger –include_dependencies”

Step 2 :  Dont forget to start debugging server by saying
ruby script/server  –debugger

Step 3 :  Say debuggger in the action, the console will open in the command line for the code written below to debugger

eg:
def foo
     debugger
     @object = Active.find(:all)
end

When in that case in the command line we will get a rbd : opened , where you can debug the object like @object.size etc

Thats it enjoy , there are some other methods like <%= debug @object %> , <%= @object.inspect %> , puts etc which I guess all of us already know abt.

, , ,

1 comment November 12, 2008

“What’s New in Edge Rails: Easy Join Table Conditions”

Just came across this new cool feature in edge rails…

For an application with anything above a moderate level of domain complexity it’s quite likely that you’ve had to perform a query utilizing a join table:

class Article < ActiveRecord::Base
belongs_to :user
end

class User < ActiveRecord::Base
has_many :articles
end

# Get all the users that have published articles
User.find(:all, :joins => :article,
:conditions => ["articles.published = ?", true])

t always makes me feel slightly embarrassed to have to resort to using String snippets to specify my query logic, and this little bit is no exception. Well, now we can specify conditions on a join table in a more concise manner:

# Get all the users that have published articles
User.find(:all, :joins => :article,
:conditions => { :articles => { :published => true } })

Note how you’re able to specify the join-table conditions as a hash whose key corresponds to the table or association name of the join table? You can now let Rails worry about forming the correct SQL condition even across complex joins.

However, don’t let the ease of this feature make you use it over a properly associated domain-model. For instance, this join query:

# Get all articles for a given user
Article.find(:all, :joins => :user,
:conditions => { :users => { :id => @user.id } })

is more appropriately represented as:

@user.articles

Technorati Tags: , , , ,

Add comment July 23, 2008

“Got introdued with conditions_by_like()”

The method MyClass.conditions_by_like(params[:search]) is not part of Active Record. It
is actually code lifted from the Streamlined framework. It provides a quick way
to search across all fields in a model.

Here is the full implementation:

def conditions_by_like(value, *columns)
columns = self.user_columns if columns.size==0
columns = columns[0] if columns[0].kind_of?(Array)
conditions = columns.map {|c|
c = c.name if c.kind_of? ActiveRecord::ConnectionAdapters::Column
“‘#{c}‘ LIKE ” + ActiveRecord::Base.connection.quote(“%#{value}%” )
}.join(” OR ” )
end

And this is actually how we use it as given in AWDWR

def search
unless params[:search].blank?
@user_pages, @users = paginate :users,
:per_page => 10,
:o rder => order_from_params,
:conditions => User.conditions_by_like(params[:search])
logger.info @users.size
else
list
end
render :partial=>’search’ , :layout=>false
end

OOps forgot to mention it comes under Active record extensions.

Add comment July 15, 2008

“Javascript made me feel like a IDIOT”

Today I was doing some javascript checks so that my regular price remains
always greater than the discounted price .

I check with normal arithmetic functions “==,<,>” to the $(“field_name”).value
and thought it has worked because that what was taught to me in my schools
that value 1 > value 2 returns true/false.

But all my prettiest school teachers were proven wrong by javascript.

I realized after releasing the code that
11> 10 => true
99.99 > 99.98 => true
212 > 212.21 => false

but they were also checking the number of digits.
So when I gave

10 > 9 => false
(It failed) …hmm even I had the same reaction!!!!

Man , what the S**T cum on how can this happen , then I thought
bro need to check javascripts arithmetic handlers once again ,
over there I came accross parseFloat and other functions.

check the link for more details

For the next two days I shall be wearing the “I was wrong ” Tshirt….

Technorati Tags: , , , , , , , , , , , ,

1 comment July 2, 2008

“Giving id to helpers in rails”

I have a text field to which I use rails helpers of text_field to create, I was wondering how can I over-write the ID of the field when I came across the below syntax.
I hope its helpful.

<%= text_field(‘policy’,’subscriber_first_name’, :size=>15, :maxlength=>50,:id=>’policy_subscriber_first_name_’+@ins_type) %>

I needed it because i was rendering same partial and at 2 instances in one page and using the ids of field to populate the fields using javascript.

Technorati Tags: , , , , ,

Add comment June 12, 2008

“Run Ruby on a JavaScript interpreter?”

&amp;lt;script type="text/ruby"&amp;gt;class Pi  def initialize 	@a = 355.0  end  def calc	b = 113.0	return @a / b  endPI = 'PI is about'	endputs Pi::PI

puts Pi.new.calc &amp;lt;/script&amp;gt;

&amp;lt;body onload="Print(); new function().runFromScriptTag('/compileRuby.cgi')"&amp;gt;

Add comment April 17, 2008

“Gambling problem”

I came accross this problem while i was surfing through some blogs here and there
The Problem =&amp;gt;

Your friend Steve is a psychic gambler. He can predict the profit or loss ofeach day of his gambling a whole month in advance. Here are his anticipatedtakings for the month...

158, 44, 196, 399, 47, 2, -158, -197, 375, 121, 806, 44, 953, 7, 20, 1, 7,88, 191, 33, 654, 156, 321, 784, -111, 159, 88, 49, 25, 366, 861, 869, 380.

So the twist is this... Steve can gamble any days he wants. He is free topick and choose, but the *casino will not let him gamble on consecutive days*(i.e. he can't gamble for 2 or more days in a row). How can he maximize hiswinnings?

Solution =&amp;gt;

#**************RUBY CODE &amp;lt;start&amp;gt;***********************

sum = Array.new

while (earnings.length &amp;gt; 0) do

a =earnings[0] unless earnings[0].nil?

b = earnings[1] unless earnings[1].nil?

c = earnings[2] unless earnings[2].nil?

d = earnings[3] unless earnings[3].nil?

if a + c &amp;gt; b + d || a + d &amp;gt; b + d then

sum &amp;lt;&amp;lt; a

2.times {earnings.shift}

else

sum &amp;lt;&amp;lt; b

3.times {earnings .shift}

end
takings_month += sum.last

end

puts ‘takings_month: ‘ + takings_month.to_s
#**************RUBY CODE &amp;lt; end &amp;gt;******************

Add comment April 8, 2008

String case handler :: reg-exp to check whether the string is upcase or not

# #This function basically checks with a regular expression whether the passed value matches with the regular expression or not ,
# #if it does then in that case it will return match data and we wont do a titleize else we will go for titleizing the data , as i am,
# #considering that the data which is a string can be of 3 formats (1/ all upcase 2/ all lowercase 3/ mixed-case), probably this wil handle all
# # the three cases .

def string_case_handler(str_value)
if (/^[A-Z]*$/.match(str_value) == nil)
#if the string doesnt matches then we will titleize it
return str_value.capitalize
else
#if we get matchdata object ,ie it gets matches , no need to do anything just print it
return str_value
end
end

Also if we want to capitalize only the first letter then replace this

str_concat = str_value.first.capitalize + str_value.slice(str_value.first.capitalize.length ,str_value.length)
return str_concat

Add comment February 14, 2008

“Rdoc commands for rails”

$ rake -T docrake doc:app              # Build the app HTML Filesrake doc:clobber_app      # Remove rdoc productsrake doc:clobber_plugins  # Remove plugin documentationrake doc:clobber_rails    # Remove rdoc productsrake doc:plugins          # Generate documation for all installed pluginsrake doc:rails            # Build the rails HTML Filesrake doc:reapp            # Force a rebuild of the RDOC filesrake doc:rerails          # Force a rebuild of the RDOC files

Powered by ScribeFire.

Add comment January 9, 2008

Previous Posts


Recent Posts

Tags

Active Record australian gp calendar date select capistrano capitalize debugging Debugging in rails edge rails formula 1 For those who dont want to update the prototype.js fun Fun baby fun google html in join javascript linus vs windows compatibility linux logging love song malaysian gp 2008 results melbourne migrations music mysql plugin poetry rails regexp regular expression results formula 1 opening race romantic poetry ror Ruby ruby on rails safe html sms song SQL string case handler for strings syantax syntax error for migrations on linux Text Area they can checkout 1.8.3 of the calender date select

Blogroll

Pages