tag:blogger.com,1999:blog-79627567049810381952023-11-15T06:28:07.963-08:00vadivelan ruby on rails blogVadivelan Kuppusamyhttp://www.blogger.com/profile/01672638241124545049noreply@blogger.comBlogger29125tag:blogger.com,1999:blog-7962756704981038195.post-62177680414165158892014-07-10T05:14:00.002-07:002014-07-10T05:14:43.007-07:00Ruby exclamation mark method<div dir="ltr" style="text-align: left;" trbidi="on">
In ruby, we see the methods with name ends with ?, !
Most of us know about the use of method name ends with ?. Ex: is_public?
We are expecting the method to return result in boolean value(true/false).
In exclamatory methods, usage is something different. See the following examples,
<blockquote>
<b>a = "A STRING" <br/>
puts a.downcase => a string <br/>
puts a => A String<br/><br/><br/>
b = "ANOTHER STRING" <br/>
puts b.downcase! => another string<br/>
puts b => another string<br/></b>
</blockquote>
For no match case, gsub will return the actual string without any change in it
<blockquote>
<b>puts "ruby on rails".gsub("none","--") => ruby on rails</b>
</blockquote>
For no match case, gsub! will return nil
<blockquote>
<b>puts "ruby on rails".gsub!("none","--").inspect</b>
</blockquote>
People call methods ends with exclamation mark is dangerous to use/careful when using it. The reason is, in some cases it will throw exception instead of false.
Ex:
<blockquote>
<b>save => return false if save fails<br/>
save! => raise an exception if save fails</b>
</blockquote>
We have a lot of exclamation mark methods in ruby, start looking on each one with their usage and start using it.<br/>
Hope it helps..<br/>
<br /></div>Unknownnoreply@blogger.com0tag:blogger.com,1999:blog-7962756704981038195.post-70064459836937367222014-07-08T00:02:00.001-07:002014-07-08T00:02:13.716-07:00Rails try method name in object<div dir="ltr" style="text-align: left;" trbidi="on">
In rails, most cases we are using the following style of code to display name, text etc..
<blockquote>
<b>user && user.name</b>
</blockquote>
It will go lengthier & is hard to maintain, check the below one
<blockquote>
<b>user && !user.comments.blank? && user.comments.first.text</b>
</blockquote>
Avoid lengthy expressions, start using "try"
<blockquote>
<b>user.try(:name)</b>
</blockquote>
It will return user name only if user object exists.
Happy coding..
<br /></div>
Unknownnoreply@blogger.com0tag:blogger.com,1999:blog-7962756704981038195.post-44123865206022153972012-07-16T02:24:00.001-07:002012-07-16T02:26:31.707-07:00Modules in Ruby - an overview<div dir="ltr" style="text-align: left;" trbidi="on">
<b>We can define any number of methods in a module. It simply holds all the defined methods and we can include/extend it in any class.</b>
<br/>
<b>If you want to use all module methods access by an instance then include the module in that class.</b>
<br/>
<b>If you want to use all module methods access by an class then extend the module in that class.</b>
<pre style="background: #ffffff; color: black;">
module Foo
def foo
puts 'foo called!'
end
end
class Bar
include Foo
end
Bar.new.foo # foo called!
Bar.foo # NoMethodError: undefined method ‘foo’ for Bar:Class
class Baz
extend Foo
end
Baz.foo # foo called!
Baz.new.foo # NoMethodError: undefined method ‘foo’ for #<Baz:0x1e708>
Hope this helps. Happy learning & coding :)
</pre>
</div>Unknownnoreply@blogger.com0tag:blogger.com,1999:blog-7962756704981038195.post-67171021235322188322012-02-28T02:28:00.002-08:002012-02-28T02:30:36.929-08:00Rails 3.1.0 - functional/integration test to test AJAXIntegration test with ajax achieved by means of calling xhr like below<br /><blockquote>xhr :req_method, :path, :parameters, :headers</blockquote><br /><blockquote>xhr :get, '/users/new' # new user action</blockquote><br /><blockquote>xhr :delete, '/users/20' # delete user</blockquote> <br />In integration test, you need to specify full path to make it work.<br /><br />Incase of Functional test, we can simply specify the name of action.<br /><br />Cheers,<br />Vadivelan.KUnknownnoreply@blogger.com0tag:blogger.com,1999:blog-7962756704981038195.post-2728941686224739662012-02-28T02:16:00.002-08:002012-02-28T02:22:03.988-08:00Authlogic login access in rails functional testWe are shifted to use Authlogic, Devise rather than rails authorization plugin/gem. We can do Integration with detailed explanations/tutorials available for Authlogic.<br /><br />In Rails test (functional/integration test in particular), we are in need to test whether the user is logged-in or not.<br />To start testing the user session, we need to use authlogic session. By using the following steps we can access Authlogic session in our rails test<br /><br />- Add the following line in your test_helper.rb<br /><blockquote>require "authlogic/test_case"</blockquote><br />- And add the method in your test_helper.rb<br /><blockquote> def user_login(user)<br />UserSession.create(user ? user : nil)<br /> end</blockquote><br />- Then inside your functional/integration test file<br /> Add this to top of all test<br /><blockquote> setup :activate_authlogic</blockquote><br />- Logged in with any existing user<br /> <blockquote>user_login(users(:last))</blockquote><br /> You are logged in.<br />- User session is accessible.<br /><br />Web application testing is much easier in Rails :)<br /><br />Cheers,<br />Vadivelan.KUnknownnoreply@blogger.com0tag:blogger.com,1999:blog-7962756704981038195.post-80539522225347251032012-02-28T02:04:00.001-08:002013-09-05T23:36:19.982-07:00Run ruby script as a background process in windows<div dir="ltr" style="text-align: left;" trbidi="on">
<div dir="ltr" style="text-align: left;" trbidi="on">
Hi Ruby folks,<br />
<br />
I went across a scenario in need of running a ruby process in background particularly in Windows OS(in Unix based system we can use '&' to run any process/job in background).<br />
<br />
To run any ruby program in background, do the following<br />
<br />
- Take a copy of the file, which you needs to run.<br />
- Save the file as .rbw extension.<br />
- Use the command <br />
<blockquote>
start "Your job description" ruby D:\Ruby\Jobs\particular_job.rbw</blockquote>
<br />
- Once it started running, You got a new console window with the given message on top and process status in console.<br />
<br />
Cheers,<br />
Vadivelan.K
</div>
<!-- GoStats JavaScript Based Code -->
<script src="http://gostats.com/js/counter.js" type="text/javascript"></script>
<script type="text/javascript">_gos='c4.gostats.com';_goa=382337;
_got=5;_goi=1;_gol='See web page stats about your site with minimal effort.';_GoStatsRun();</script>
<noscript><a target="_blank" title="See web page stats about your site with minimal effort."
href="http://gostats.com"><img alt="See web page stats about your site with minimal effort."
src="http://c4.gostats.com/bin/count/a_382337/t_5/i_1/counter.png"
style="border-width:0" /></a></noscript>
<!-- End GoStats JavaScript Based Code --></div>
Unknownnoreply@blogger.com0tag:blogger.com,1999:blog-7962756704981038195.post-84296228218228825282011-10-20T02:26:00.000-07:002011-10-20T02:59:49.210-07:00SolrIntegrating SOLR search into our application. “acts_as_solr” is the name of the plugin(also available as gem).<br />Install plugin:<br /><pre style='color:#000000;background:#ffffff;'>script<span style='color:#808030; '>/</span>plugin install git:<span style='color:#808030; '>/</span><span style='color:#808030; '>/</span>github<span style='color:#808030; '>.</span>com<span style='color:#808030; '>/</span>mattmatt<span style='color:#808030; '>/</span>acts_as_solr<span style='color:#808030; '>.</span>git<br /></pre><br />Install gem:<br /><pre style='color:#000000;background:#ffffff;'>gem install acts_as_solr<br /></pre><br /><br />Add the below line into your application's configuration file<br /><pre style='color:#000000;background:#ffffff;'>config<span style='color:#808030; '>.</span>gem <span style='color:#0000e6; '>"acts_as_solr"</span><br /></pre><br />Add this at the end of your Rakefile(only for using gem)<br /><pre style='color:#000000;background:#ffffff;'><span style='color:#400000; '>require</span> <span style='color:#0000e6; '>'aas_tasks'</span><br /></pre><br />After installing gem/plugin, following rake tasks are available to use<br />rake solr:destroy_index # Remove Solr index<br />rake solr:reindex # Reindexes data for all ac<br />ts_as_solr models.<br />rake solr:start # Starts Solr.<br />rake solr:stop # Stops Solr.<br />We can start, stop, reindex, destroy index by using the mentioned rake tasks.<br /><br /><br />Add the following rake task inside the solr rake file(gems/acts_as_solr/lib/tasks/solr.rake), to start solr in Windows environment.<br /><pre style='color:#000000;background:#ffffff;'>desc <span style='color:#0000e6; '>"Starts Solr. on windows . Options accepted: RAILS_ENV=your_env, PORT=XX. Defaults to development if none."</span><br /> task :start_win <span style='color:#800000; font-weight:bold; '>do</span><br /> <span style='color:#400000; '>require</span> <span style='color:#0000e6; '>"#{File.dirname(__FILE__)}/../../config/solr_environment.rb"</span><br /> <span style='color:#800000; font-weight:bold; '>begin</span><br /> n <span style='color:#808030; '>=</span> Net::HTTP<span style='color:#808030; '>.</span><span style='color:#800000; font-weight:bold; '>new</span><span style='color:#808030; '>(</span><span style='color:#0000e6; '>'localhost'</span>, SOLR_PORT<span style='color:#808030; '>)</span><br /> n<span style='color:#808030; '>.</span>request_head<span style='color:#808030; '>(</span><span style='color:#0000e6; '>'/'</span><span style='color:#808030; '>)</span><span style='color:#808030; '>.</span>value<br /><br /> <span style='color:#800000; font-weight:bold; '>rescue</span> Net::HTTPServerException <span style='color:#696969; '>#responding</span><br /> <span style='color:#400000; '>puts</span> <span style='color:#0000e6; '>"Port #{SOLR_PORT} in use"</span> <span style='color:#800000; font-weight:bold; '>and</span> <span style='color:#800000; font-weight:bold; '>return</span><br /><br /> <span style='color:#800000; font-weight:bold; '>rescue</span> Errno::ECONNREFUSED <span style='color:#696969; '>#not responding</span><br /> Dir<span style='color:#808030; '>.</span>chdir<span style='color:#808030; '>(</span>SOLR_PATH<span style='color:#808030; '>)</span> <span style='color:#800000; font-weight:bold; '>do</span><br /> <span style='color:#400000; '>exec</span> <span style='color:#0000e6; '>"java -Dsolr.data.dir=solr/data/#{ENV['RAILS_ENV']} -Djetty.port=#{SOLR_PORT} -jar start.jar"</span><br /> <span style='color:#400000; '>sleep</span><span style='color:#808030; '>(</span><span style='color:#008c00; '>5</span><span style='color:#808030; '>)</span><br /> <span style='color:#400000; '>puts</span> <span style='color:#0000e6; '>"#{ENV['RAILS_ENV']} Solr started sucessfuly on #{SOLR_PORT}, pid: #{pid}."</span><br /> <span style='color:#800000; font-weight:bold; '>end</span><br /> <span style='color:#800000; font-weight:bold; '>end</span><br /> <span style='color:#800000; font-weight:bold; '>end</span><br /></pre><br /><br /><br />Steps to configure solr in our application<br /><br />1) Starts the solr server<br /><pre style='color:#000000;background:#ffffff;'>rake solr:start<br /></pre><br /><br />2) Changes to ActiveRecord model<br /> acts_as_solr - all fields are indexed<br /><pre style='color:#000000;background:#ffffff;'><span style='color:#800000; font-weight:bold; '>class</span> News < ActiveRecord::Base<br /> acts_as_solr :fields <span style='color:#808030; '>=</span>> <span style='color:#808030; '>[</span>:title, :content<span style='color:#808030; '>]</span> <br /> <span style='color:#800000; font-weight:bold; '>end</span><br /></pre><br /> – specified fields are indexed<br />We can specify the name of the fields to be used for searching.<br /> Options:<br /> :if => we can supply any condition as string, proc, symbol, method. It will index the record only if condition returns true.<br /><br />3) Do index/reindex<br /><pre style='color:#000000;background:#ffffff;'>rake solr:reindex<br /></pre><br /><br />4) Changes to Controller<br /><pre style='color:#000000;background:#ffffff;'>News<span style='color:#808030; '>.</span>find_by_solr<span style='color:#808030; '>(</span>query<span style='color:#808030; '>)</span><br /></pre><br />query => query is a string representing your query<br /> <br />There are many options available in solr, we can do a refined search by using SOLR.<br /><br />Problem:<br />I faced one problem, acts_as_solr :if option is not working with rake task to reindex data. Instead of checking the condition it will simply indexes all the records. But other method like solr_save() checks the condition passed with acts_as_solr definition in model. I have added a patch to check the condition in rake task 'reindex'.<br /><br />file path: acts_as_solr\lib\class_methods.rb<br />line no: 200 - 250<br />method name: rebuild_solr_index<br />Instead of normal collect,<br /><pre style='color:#000000;background:#ffffff;'>items<span style='color:#808030; '>.</span>collect! <span style='color:#800080; '>{</span> |content| content<span style='color:#808030; '>.</span>to_solr_doc <span style='color:#800080; '>}</span><br /></pre><br /><br />We can use the following code, to filter the records with the condition defined in model and collect the remaining results<br /><pre style='color:#000000;background:#ffffff;'>items <span style='color:#808030; '>=</span> items<span style='color:#808030; '>.</span><span style='color:#400000; '>select</span> <span style='color:#800080; '>{</span> |content| content<span style='color:#808030; '>.</span>evaluate_condition_public<span style='color:#808030; '>(</span>content<span style='color:#808030; '>)</span><span style='color:#800080; '>}</span><br />items<span style='color:#808030; '>.</span>collect! <span style='color:#800080; '>{</span> |content| content<span style='color:#808030; '>.</span>to_solr_doc <span style='color:#800080; '>}</span><br /></pre><br /><br />After doing the above changes, you can have a correct data in your search results. This is applicable only when we are using acts_as_solr with conditions in model.<br /><br /><pre style='color:#000000;background:#ffffff;'>acts_as_solr :fields <span style='color:#808030; '>=</span>> <span style='color:#808030; '>[</span><span style='color:#0000e6; '>"name"</span>,<span style='color:#0000e6; '>"description"</span><span style='color:#808030; '>]</span>, :<span style='color:#800000; font-weight:bold; '>if</span> <span style='color:#808030; '>=</span>> <span style='color:#400000; '>proc</span><span style='color:#800080; '>{</span>|record| record<span style='color:#808030; '>.</span>active?<span style='color:#800080; '>}</span><br /></pre><br /><br />Hope, this is useful for someone who is using acts_as_solr with :if option.<br /><br />Cheers,<br />VadivelanUnknownnoreply@blogger.com0tag:blogger.com,1999:blog-7962756704981038195.post-32625367617483316952011-08-18T04:18:00.000-07:002011-08-18T04:27:50.580-07:00Functional Testing in Rails(to test Html)Hi all,
<br />
<br />I have used listed out some uses of assert_tag in Rails functional test. In many case, we need to test the html content of page like checkbox is checked or not, text fields holds correct value, drop down selected with correct option. For those kind of needs, we need to go for <span style="font-style:italic;">assert_tag</span>. Below are the example usage of assert_tag in functional testing.
<br />
<br />In Rails html testing, assert_tag method plays an vital role. Following are some of the ways to use assert_tag method
<br />
<br />
<br />Get links inside div
<br />
<br />assert_select "div#divID" do
<br /> assert_select "a[href=?]", "/path/to/some/page"
<br />end
<br />
<br />Check the content of any html element(here is an example for Div)
<br />
<br /> by className
<br /> assert_select "div.className", "Page Heading or content inside the div"
<br /> by element ID
<br /> assert_select "div#elementId", "Page Heading or content inside the div"
<br />
<br />Check how many times any DOM element appears on the page:
<br />
<br />In the below example, we tested how many number of user images loaded on the page
<br />assert_select "div.className table tr td.userImage img", {:count => 4}
<br />
<br />Presence of Textbox:
<br />
<br />assert_tag "input", :attributes => {:id => "user_screen_name", :size => "30", :type => "text"}
<br />
<br />Get value of Dropdown:
<br />
<br />option = css_select("select#elementId option[selected='selected']")[0]
<br />assert_equal "public", option['value'].to_s
<br />
<br />Code with testcase improves the quality of code and at the sametime reduces the errors. Keep writing test for each line of code.Unknownnoreply@blogger.com0tag:blogger.com,1999:blog-7962756704981038195.post-25692589730835825172011-04-18T06:41:00.000-07:002011-10-20T02:59:15.810-07:00Alternative to "grep" command in WindowsHi all,<br /><br />I have shifted from ubuntu and started using windowsXP. When I tried to use the grep command in windows, it throws the error<br /><br />Instead of using grep, we can use find<br /><pre style='color:#000000;background:#ffffff;'>gem list|find <span style='color:#0000e6; '>"rails"</span><br /></pre><br />rails (3.0.10)<br /><br />Cheers,<br />VadivelanUnknownnoreply@blogger.com0tag:blogger.com,1999:blog-7962756704981038195.post-54706312683522439532011-02-02T01:27:00.000-08:002011-02-02T01:37:01.396-08:00Month with number of count display for any model in your applicationBy using rails finder method, it is very easy to display the number of post and month accordingly.<br />Here is the query<br /><br />>> Post.count(:order => 'DATE(created_at) DESC', :group => ["DATE_FORMAT(created_at,'%m/%Y')"])<br />=> #< OrderedHash {"06/2010"=>1, "03/2010"=>1, "02/2010"=>1}><br /><br />Result is a collection hash ordered in the form of latest month as first one, Collection contains the month as Key and number of count as Value. <br /><br />If we run it through the each loop and it is very easy to display.<br /><br />Thanks,<br />VadivelanUnknownnoreply@blogger.com1tag:blogger.com,1999:blog-7962756704981038195.post-75654513315353389592011-01-10T00:47:00.000-08:002011-01-10T00:49:23.519-08:00Ruby keywordsList of ruby keywords<br /><br />1. alias<br />2. and<br />3. BEGIN<br />4. begin<br />5. break<br />6. case<br />7. class<br />8. def<br />9. defined<br />10. do<br />11. else<br />12. elsif<br />13. END<br />14. end<br />15. ensure<br />16. false<br />17. for<br />18. if<br />19. in<br />20. module<br />21. next<br />22. nil<br />23. not<br />24. or<br />25. redo<br />26. rescue<br />27. retry<br />28. return<br />29. self<br />30. super<br />31. then<br />32. true<br />33. undef<br />34. unless<br />35. until<br />36. when<br />37. while<br />38. yieldUnknownnoreply@blogger.com0tag:blogger.com,1999:blog-7962756704981038195.post-65325959026795335132011-01-09T23:32:00.000-08:002011-01-10T00:46:55.943-08:00SQL order_by "field" optionHi all,<br /><br />I tried to order the SQL results in a pre-defined order. Consider the case<br /><br />Am having users table, and a field called 'status' to store the current status of the user.<br />In back-end of my site, am displaying all the users with order-by 'status'<br /><br />Possible status values are "Pending", "Approved", "Canceled", "Deleted"<br /><br />I need to display users in the following orders, <br />"Approved", "Pending", "Canceled", "Deleted"<br /><br />The normal order by field orders the field in either ASC/DESC. But in this case it is different.<br />For this i used the following query to fetch SQL results in a defined order<br /><br />Rails finder: <br /><span style="font-weight:bold;">User.find_by_sql("select * from users order by field (status,'Approved', 'Pending', 'Canceled', 'Deleted')")</span><br /><br />SQL query:<br /><span style="font-weight:bold;">select * from users order by field (status,'Approved', 'Pending', 'Canceled', 'Deleted');</span><br /><br />Result contains the collection in the defined order.<br /><br />When you are using this "order by field" option, you have to give all the option in the order then only it will works.<br /><br />Thanks,<br />VadivelanUnknownnoreply@blogger.com1tag:blogger.com,1999:blog-7962756704981038195.post-36259725895997483832010-11-10T19:28:00.000-08:002010-11-10T19:30:23.797-08:00ActiveRecord::Base increment & decrement methodHi all,<br /><br />Yesterday while i was working in a task, i need to increase the points of an user. For that i have used the update_attribute method like below<br /> <br />user = User.last <br />user.update_attribute(:points, 5)<br /><br />Then i found the active record base in-built method called "increment" and "decrement". So i used the following method to increment/decrement the user points. <br /><br />user.increment(:points) # it will increase points by 1(default increment count) and returns the user object(self)<br />user.save<br />user.increment!(:points) # and this one will do the above two operations i.e., assigns the value to the attribute and saves the record. It will returns true or false(validation result).<br /><br />user.increment(:points, 5) # we can pass the value like this to increment the attribute by this much. Here points will increases by 5<br />user.save<br />user.increment!(:points, 5)<br /><br />The same is applicable to the "decrement" method, syntax is given below<br />user.decrement(:points)<br />user.decrement!(:points)<br />user.decrement(:points, 5)<br />user.decrement!(:points, 5)<br /><br /><br />Thanks,<br />VadivelanUnknownnoreply@blogger.com0tag:blogger.com,1999:blog-7962756704981038195.post-29067167067847685042010-10-06T21:52:00.000-07:002010-10-06T22:10:04.192-07:00Use of rails consoleHi all,<br /><br />We can use our rails console(powerful tool for rails app) for debugging and testing. Mainly console helps us to learn more about Ruby<br /> <br />Normally we are using console to talk with our database, and fetch the objects from db.<br />ex: <br />User.first<br />User.all<br /><br />But apart from that we can use our console to interact with our application using the object "app"<br />"app"<br /><br />app.class # returns this<br />ActionController::Integration::Session<br /><br />we can fire(get/post) requests to our application from console itself.<br /><br />>> app.get "/login"<br />=> 200<br />it returns the status code for the handled request<br /> <br />>> app.post "/user_sessions", :user_session => {:email => 'vadivelan@example.com', :password => 'secret'}<br />=> 302<br />we can send post request with parameters like this<br /><br />>> app.response.redirect?<br />=> true<br />redirected to some other url<br /><br />>> app.response.redirect_url<br />=> "http://localhost/login"<br />view the redirect url <br /><br />Hope now you guys can start firing the requests to application from console.<br /><br />Thanks,<br />VadivelanUnknownnoreply@blogger.com0tag:blogger.com,1999:blog-7962756704981038195.post-81402320249667949062010-09-24T04:56:00.000-07:002010-09-27T07:06:26.172-07:00ruby send methodHi all<br /><br />I am started using the method named "send".<br /><br />We can use this to call the method using object.<br /><br />class User<br /><div style="text-align: left;"> <br />def say_hello<br />"Hello"<br />end <br /></div><br />end<br /><br />u = User.new<br />puts u.send(:say_hello)<br /><br />Here the class "User" is having the method called say_hello. We can create an object for the user class and call the method using the method "send"<br /><br />Cheers,<br />vadivelanUnknownnoreply@blogger.com0tag:blogger.com,1999:blog-7962756704981038195.post-74328952917613505392010-09-21T11:14:00.000-07:002010-09-21T11:26:50.250-07:00ruby extend methodHi all,<br /><br />I have seen the method named "extend" used in a line of code in Plugin. Then i started searching for the use of method "extend". And i found the following<br /><br />consider the example<br /><br />module Friend<br /> def say_hello<br /> "hello am inside module"<br /> end<br />end<br /><br />class Person<br /> def say_hello<br /> "hello am inside class"<br /> end<br />end<br /><br />p = Person.new<br />puts p.say_hello #=> hello am inside class<br /><br />p.extend(Friend) #=> include all the instance method from Module "Friend"<br />puts p.say_hello #=> hello am inside module<br /><br /><br />So the extend method is used to include the Module.<br />Without this we cannot call the method inside the module using the Person object. Even if i added include the module in the class, it wont calls the module method. The instance method inside the class gets called for the object(Person class).Unknownnoreply@blogger.com0tag:blogger.com,1999:blog-7962756704981038195.post-26511991113337360162010-09-15T23:54:00.000-07:002010-09-16T00:08:22.200-07:00Use of Proc & procHi <br /><br />I have used "proc" to run/block validation in model. But now i learned something more about proc. <br />In ruby, "Proc"(procedure) refers to the block of code, we can reuse it. Block of code assigned to the object.<br /><br />"Proc" => Starts with capital letter refers to (class name)<br />"proc" => Refers to the proc object<br /><br />We can use both the keywords to create a proc by defining any block to them.<br /><br />below sample code to create a proc and call that proc to execute the block of code<br /><br />accepts_any_arg = Proc.new{ |a,b,c|<br /> puts "#{a} #{b} #{c}"<br />}<br />accepts_any_arg.call(1)<br /> result: 1<br />accepts_any_arg.call(1,2) <br /> result: 1 2<br />It just neglects the number of arguments required or passing to that proc, it is working without any argument error. It assigns nil value to arguments which are not passed.<br /><br /><br />throws_args_error = proc{ |a,b,c|<br /> puts "#{a} #{b} #{c}"<br />}<br />throws_args_error.call(1,2,3)<br /> result: 1 2 3<br />throws_args_error.call(1)<br /> result: Throws "ArgumentError"<br />it is checking the number of arguments<br /><br /><br />Thanks,<br />VadivelanUnknownnoreply@blogger.com0tag:blogger.com,1999:blog-7962756704981038195.post-68022532900249537392010-07-22T08:10:00.001-07:002010-07-22T08:18:35.071-07:00Ruby - "defined?" methodHi all,<br /><br />In ruby we are having many methods to check whether the variable defined or not. Mostly we are using the following condition to check the variable defined or not<br /><br />Code:<br />if local_variable<br /> puts "local variable exists"<br />else<br /> puts "local_variable does not exists"<br />end <br /><br />But there is another way to check the variable defined or not.<br /><br />sample-code:<br /><br />a = 10<br />puts defined?(a).inspect => "local-variable"<br />puts defined?(b).inspect => nil<br /><br />So, the method returns the value "local-variable" for the already defined variables and "nil" for the undefined variables.<br /><br />Hope hereafter you guys using the method "defined?" to check the variable already defined or not.<br /><br />Cheers,<br />VadivelanUnknownnoreply@blogger.com0tag:blogger.com,1999:blog-7962756704981038195.post-74899769983906181182010-05-24T20:54:00.000-07:002010-05-24T21:05:30.750-07:00ruby math functionsHi all,<br /><br />Here i have listed some of the most frequently used math functions in ruby.<br /><br />round method rounds the value <br />if decimal value is less than .5, rounded to its lowest value<br />irb(main):006:0> 1.2.round<br />=> 1<br />if decimal value is greater than .4, rounded to its highest value<br />irb(main):007:0> 1.5.round<br />=> 2<br /><br />floor method rounded the value to lowest value<br />irb(main):008:0> 1.5.floor<br />=> 1<br /><br />ceil method rounded the value to next highest value<br />irb(main):009:0> 1.5.ceil<br />=> 2<br /><br />'nan' method used to check whether the value is integer or not<br />irb(main):010:0> x = 0.0/0.0<br />=> NaN<br /><br />irb(main):011:0> x.nan?<br />=> true<br /><br />Get ASCII value<br />irb(main):017:0> Integer(?e)<br />=> 101<br /><br />irb(main):018:0> Float(?e)<br />=> 101.0<br /><br />>> "%.2f" % (1.0/2.0)<br />=> "0.50"<br /><br />The last method is mainly used for display purpose. We have to display the floating point number in any page(say to display the cost) we must modify the output in such a way to get clear display(Max of 2 numbers after decimal point in this case).<br /><br /><br />Thanks,<br />VadivelanUnknownnoreply@blogger.com0tag:blogger.com,1999:blog-7962756704981038195.post-44581955908735194952010-05-24T20:45:00.000-07:002010-05-24T20:53:41.426-07:00Some more uses of '$' in prototype javascriptHi all,<br /><br />We are all using the '$' in prototype javascript to get the object of the matched DOM element by using id of the element.<br /><br />Say for example:<br /><br />the page has the div element <br /><div id='container'><br /> content inside the div element <br /></div><br /><br />To get the object of the div element we are using the '$'.<br /><br />$('container') => returns the object of the DOM element.<br /><br />$A/$W/$F => are also available but rarely used..<br /><br />the below lines explain the use of the $A/$W/$F<br /><br />// converts a string into array, each element is taken as a count<br />>>> $A('1')<br />['1']<br />>>> $A('123')<br />["1", "2", "3"]<br /><br />// converts a string into array, it takes whitespace as delimiters<br />>>> $w('1 2 3')<br />["1", "2", "3"]<br /><br />// used to get values of text field which is located inside any forms<br />// same as Form.Element.getValue<br />>>> $F('press_room_url')<br /><br />So start using these commands makes the code simpler.. <br /><br /><br />Thanks,<br />VadivelanUnknownnoreply@blogger.com0tag:blogger.com,1999:blog-7962756704981038195.post-10879276647167737922010-03-31T21:48:00.000-07:002010-03-31T21:57:14.935-07:00jQuery with railsHi all,<br /><br />I have used the jquery js prototype recently, it has lots of more usage than our prototype.js. Easy to code using jQuery.js.<br /><br />But in my rails application i have used both prototype.js & jquery.js. In this situation the $ gets conflict. To avoid conflict, use the line of code<br /><br />First include prototype.js, then add jQuery.js after that you must add this line to avoid ($)conflict<br /><script><br />var $j = jQuery.noConflict();<br /></script><br /><br />Once you done this, you can enjoy the usage of both prototype.js & jQuery.js.<br /><br />i.e., both $ and $j is available to access.<br /><br />$('id_of_dom_elemnt') => returns (prototype)object of the html element<br />$j('#id_of_dom_element') => return (jquery)object of the html element<br /><br />In jQuery, we have to add '#' symbol with id of dom element to find the element.<br /><br />Enjoy coding with jQuery... <br /><br />thanks,Unknownnoreply@blogger.com0tag:blogger.com,1999:blog-7962756704981038195.post-49230377093226848982010-01-23T02:04:00.000-08:002010-01-23T02:13:44.992-08:00JSON startupJSON - javascript object notation<br /><br />To know about the JSON, first go through the following basics in js.<br /><br />Array:<br /><br />var arr = new Array("first", "second", "third", "fourth");<br /><br />Retrieve value from array<br /><br />arr[0] => "first"<br />arr[1] => "second"<br /><br /><br />Object:<br /><br />var sample_object = {<br /> "name1" : "value1",<br /> "name2" : "value2",<br /> "name3" : "value3",<br /> "name4" : "value4"<br />}<br /><br />sample_object.name1 => "value1"<br />sample_object["name1"] => "value1"<br /><br /><br /><br />Objects in Array<br /><br />var object_array = [<br /> {<br /> "first_element" : "first_value"<br /> },<br /> {<br /> "second_element" : "second_value"<br /> }<br />]<br />object_array[0] => returns first object <br />object_array[1].second_element => second object value<br /><br /><br />Arrays in Object:<br /><br />var sample_object = {<br /> "name1" : "value1",<br /> "name4" : [1,2,3,4]<br />}<br />sample_object.name4 => [1,2,3,4]<br />sample_object.name4[0] => 1<br /><br />var str_json = JSON.stringify(sample_object);<br />var js_object = JSON.parse(str_json);<br />JSON.parse(strJSON) - converts a JSON string into a JavaScript object.<br />JSON.stringify(objJSON) - converts a JavaScript object into a JSON string.Unknownnoreply@blogger.com0tag:blogger.com,1999:blog-7962756704981038195.post-46700386961275298512009-12-07T18:33:00.000-08:002009-12-07T18:42:37.593-08:00Watir tipsHi Guys,<br /><br />Waitr is a ruby gem used in testing. It has many uses, mostly it is used to control the web browser(all html dom elements as objects).<br /><br />installation command:-<br />gem install waitr<br /><br />Some sample use of watir<br /><br />1. Starting a new Web browser<br />require 'watir'<br />ie = Watir::Browser.new<br />ie.goto("http://www.google.com")<br /><br />2. Starting a firefox browser<br />require 'watir'<br />Watir::Browser.default = "firefox"<br />ff = Watir::Browser.start("http://www.google.com")<br /><br />3.Setting a text field with some value<br /><br />ie.text_field(:name, "username").set "Vaddi"<br /><br />4. Setting value of select list<br /><br />ie.select_list( :name , "category").select("Comedy")<br /><br />For all the DOM elements, it has objects(for text box - 'text_field', for drop down - 'select_list')<br /><br />thanks,Unknownnoreply@blogger.com0tag:blogger.com,1999:blog-7962756704981038195.post-52536031305913917842009-12-04T18:46:00.000-08:002009-12-04T21:44:50.565-08:00for loop - jsIn javascript, to read the array index and their appropriate value.<br /><br />Use the following way,<br /><br />var a = Array.new(); declare new array with name 'a'<br />a = [1,2,3,4,5]; assign some values to array<br />var indexes = function show(value, indx){<br /> alert(indx);<br /> alert(value);<br />}<br />a.forEach(indexes);<br />'forEach' method is used to collect the values from the array.<br /><br />By using the method 'forEach', we can collect each element from array.<br /><br />Try this..Unknownnoreply@blogger.com0tag:blogger.com,1999:blog-7962756704981038195.post-32387779313716794122009-11-30T01:06:00.000-08:002009-11-30T01:10:51.119-08:00Add favicon image to your siteIts very easy to add favicon to ur site by following steps<br /><br />include the line in your layout head<br />html link tag <br />with attributes <br />rel="icon" href="favicon_path" <br />type="image/x-icon"<br /><br />favicon_path = image path of favicon<br /><br />That's it...<br /><br />Try with this..Unknownnoreply@blogger.com0