<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0"
	xmlns:content="http://purl.org/rss/1.0/modules/content/"
	xmlns:wfw="http://wellformedweb.org/CommentAPI/"
	xmlns:dc="http://purl.org/dc/elements/1.1/"
	xmlns:atom="http://www.w3.org/2005/Atom"
	xmlns:sy="http://purl.org/rss/1.0/modules/syndication/"
	xmlns:slash="http://purl.org/rss/1.0/modules/slash/"
	>

<channel>
	<title>eXpand yOur cReativity &#187; ruby</title>
	<atom:link href="http://blog.bhushangahire.net/tag/ruby/feed/" rel="self" type="application/rss+xml" />
	<link>http://blog.bhushangahire.net</link>
	<description></description>
	<lastBuildDate>Thu, 05 Jan 2012 07:17:32 +0000</lastBuildDate>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.org/?v=3.3</generator>
		<item>
		<title>Setup script to get Ruby and Rails running on Ubuntu with one command using RailsReady</title>
		<link>http://blog.bhushangahire.net/2011/12/05/setup-script-to-get-ruby-and-rails-running-on-ubuntu-with-one-command-using-railsready/?utm_source=rss&#038;utm_medium=rss&#038;utm_campaign=setup-script-to-get-ruby-and-rails-running-on-ubuntu-with-one-command-using-railsready</link>
		<comments>http://blog.bhushangahire.net/2011/12/05/setup-script-to-get-ruby-and-rails-running-on-ubuntu-with-one-command-using-railsready/#comments</comments>
		<pubDate>Mon, 05 Dec 2011 10:29:26 +0000</pubDate>
		<dc:creator>Bhushan Ahire</dc:creator>
				<category><![CDATA[git]]></category>
		<category><![CDATA[Rails]]></category>
		<category><![CDATA[ruby]]></category>
		<category><![CDATA[Subversion]]></category>
		<category><![CDATA[railsready]]></category>
		<category><![CDATA[server]]></category>

		<guid isPermaLink="false">http://blog.bhushangahire.net/?p=302</guid>
		<description><![CDATA[How would you like to get a full Ruby on Rails stack up on Ubuntu with one command? Now you can by running Rails Ready. Rails Ready is a setup script that gets Ruby and Rails running on a fresh install of Ubuntu with one command (Tested on Ubuntu server 10.04 LTS (Long-term Support)). This [...]]]></description>
			<content:encoded><![CDATA[<div class="description">
<p>How would you like to get a full Ruby on Rails stack up on Ubuntu with one command?</p>
<p>Now you can by running Rails Ready. Rails Ready is a setup script that gets Ruby and Rails running on a fresh install of <a target="_blank" class="link external" href="http://www.ubuntu.com/">Ubuntu</a> with one command (Tested on Ubuntu server 10.04 LTS (Long-term Support)).</p>
<p>This is a brand new project by <a target="_blank" class="link external" href="https://github.com/joshfng">Josh Frye</a> that he uses all the time to setup VMs, but there’s always testing to be done and improvements to be made. </p>
<h3>Running the&nbsp;Script</h3>
<p>Check out <a target="_blank" class="link external" href="https://github.com/joshfng/railsready/blob/master/railsready.sh">railsready.sh</a> to see everything Rails Ready is doing.</p>
<pre class="brush: ruby">
  sudo wget --no-check-certificate https://github.com/joshfng/railsready/raw/master/railsready.sh &amp;amp;amp;&amp;amp;amp; bash railsready.sh
</pre>
<p>The script will then ask if you want to build Ruby from source or install RVM. If you want to watch the magic happen just run <code>tail -f ~/railsready/install.log</code>.</p>
<h3>What gets installed?</h3>
<ul>
<li>An updated system (Linux only)</li>
<li>Homebrew (OSX only)</li>
<li>Ruby 1.9.3 latest patch level (installed to /usr/local/bin/ruby) or RVM running 1.9.3 latest patch level</li>
<li>Imagemagick</li>
<li>libs needed to run Rails (sqlite, mysql, etc)</li>
<li>Bundler, Passenger, and Rails gems</li>
<li>Git</li>
</ul>
<p>All you need to do is install <a target="_blank" class="link external" href="http://nginx.org/">NGINX</a> or <a target="_blank" class="link external" href="http://www.apache.org/">Apache</a>, run <code>passenger-install-nginx-module</code> or <code>passenger-install-apache-module</code>, upload your app, point your vhost config to your apps public directory and go!</p>
<p>A note about RVM+passenger+nginx: Passenger installed via RVM can&#8217;t locate the OpenSSL package installed on Ubuntu. A user contributed fix is as follows:</p>
<pre class="brush: ruby">
rvm remove 1.9.2
rvm package install openssl
rvm install 1.9.2 --with-openssl-dir=$HOME/.rvm/usr
rvmsudo passenger-install-nginx-module
</pre>
<p>Hope this guide will be helpful to you.
</p></div>
]]></content:encoded>
			<wfw:commentRss>http://blog.bhushangahire.net/2011/12/05/setup-script-to-get-ruby-and-rails-running-on-ubuntu-with-one-command-using-railsready/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Removing &#8220;out of sync&#8221; error in acts_as_solr</title>
		<link>http://blog.bhushangahire.net/2010/10/05/removing-out-of-sync-error-in-acts_as_solr/?utm_source=rss&#038;utm_medium=rss&#038;utm_campaign=removing-out-of-sync-error-in-acts_as_solr</link>
		<comments>http://blog.bhushangahire.net/2010/10/05/removing-out-of-sync-error-in-acts_as_solr/#comments</comments>
		<pubDate>Tue, 05 Oct 2010 04:52:28 +0000</pubDate>
		<dc:creator>Bhushan G Ahire</dc:creator>
				<category><![CDATA[JRuby]]></category>
		<category><![CDATA[Rails]]></category>
		<category><![CDATA[ruby]]></category>
		<category><![CDATA[acts_as_solr]]></category>
		<category><![CDATA[apache]]></category>
		<category><![CDATA[lucane]]></category>
		<category><![CDATA[solr]]></category>

		<guid isPermaLink="false">http://blog.bhushangahire.net/?p=230</guid>
		<description><![CDATA[Solr is an open source enterprise search server based on the Lucene Java search library, with XML/HTTP and JSON APIs, hit highlighting, faceted search, caching, replication, a web administration interface and many more features. It runs in a Java servlet container such as Tomcat.  -Apache Solr Solr can be used in different containers and different wrappers. [...]]]></description>
			<content:encoded><![CDATA[<blockquote><p><a href="http://lucene.apache.org/solr/">Solr</a> is an open source enterprise<br />
search server based on the Lucene Java search library, with XML/HTTP and JSON APIs, hit highlighting, faceted search, caching, replication, a web administration interface and many more features. It runs in a Java servlet container such as Tomcat.  -<a href="http://lucene.apache.org/solr/">Apache Solr</a></p></blockquote>
<p>Solr can be used in <a href="http://wiki.apache.org/solr/#head-f5e0c63a9a48037a2200cf9ceabda53898142d80">different containers</a> and <a href="http://wiki.apache.org/solr/#head-ab1768efa59b26cbd30f1acd03b633f1d110ed47">different wrappers</a>.  Our application runs on Ruby on Rails, and we used <a href="http://github.com/railsfreaks/acts_as_solr/tree/master">acts_as_solr</a>.  Though solr is a powerful, already stable and yet flexible third party solution that we could rely on, we were still not able to maximize its full capacity.  We used the bare minimum features of solr for our search modules.</p>
<p>As of now, we&#8217;ve used a couple of acts_as_solr enhancments and add ons, some of which we learned from different online resources.  We were able to use <a href="http://www.elctech.com/projects/advanced-db_free_solr">db_free_solr</a> and explored on the <a href="http://www.quarkruby.com/2007/9/14/advanced-acts_as_solr">highlighting and faceting capabilities of solr</a>.  Its been pretty helpful, but of course nothing is almost always seamless.  We encounter few problems with syncing records from the database and onto solr.  For sure, you&#8217;ve come across this trouble before, if you&#8217;ve been using solr:</p>
<blockquote><p>Out of sync! Found N items in index, but only n were found in database!</p></blockquote>
<p>It sure was putting down every page wherein there was this glitch in the count of the records retrieved.  It therefore gave the negative impression that our site was frequently unstable.  Removing a certain indexed element from the solr index is easy as:</p>
<pre class="brush: ruby">
ActsAsSolr:: Post.execute(Solr::Request:: Delete.new(:query =&amp;gt; %{type_s:Model AND id:&amp;quot;Model:110809&amp;quot;}))
ActsAsSolr:: Post.execute(Solr::Request::Commit.new)
</pre>
<p>It could&#8217;ve been pretty straightforward removing this concerned item from the solr index and then everything would be well.. but its a lot harder than that if you&#8217;re looking at over a thousand indexed elements vs their &#8216;existing&#8217; counterparts in the database!  Finding the exact data to remove was really the hardest part!  I never knew this until I took the liberty of helping out our kind Infra Team to resolve the problem.   I decided to tweak the solr parser method returning the &#8220;out of  sync&#8221; error.  I thought that it would actually be brilliant to just display the concerned element&#8217;s id so that they could delete it from the index itself.  And so, I had something like this: (in acts_solr/lib/parser_methods.rb)</p>
<pre class="brush: ruby">
raise &amp;quot;Out of sync! Found #{ids.size} items in index, but only #{things.size} were found in database! Remove #{(ids - (things.collect{|x| x.id})).to_sentence}.&amp;quot; unless things.size == ids.size
</pre>
<p>And yes, viola!  I can now see the faulty ids that were causing the &#8220;out of sync&#8221; problem.  I presented this not-so-brilliant solution to our Infra Team, and they came up with a better idea.  My colleague thought that it would be nicer if I could just do away with the &#8220;out of sync&#8221; error altogether. Since I can already pinpoint the cause of the trouble, then why not remove it for good?  I came up with half the solution.  It was the quicker one to implement and didn&#8217;t require much from their end either.</p>
<p>Distinguishing the faulty id from the list of objects from solr vs those that were from the db, it paved the way for me to simply remove these ids from the checking.  It was half the solution because (hint, hint.. I may be doing this next time when I have time) I could actually delete the certain indexed element from solr instead of simply removing it from solr&#8217;s items on hand.  This &#8220;full&#8221; solution could actually bring forth other complications since you&#8217;d have to deal with what models were concerned and what fields will solr need to look at, etc.</p>
<p>And so.. the half solution that I did was to clean up the elements on hand for solr.  This <a href="http://pastie.org/pastes/426482">snippet</a> is found in acts_as_solr/lib/parser_methods.rb.</p>
<pre class="brush: ruby">
 def reorder(things, ids)
    ordered_things = Array.new(things.size)

    unless things.size == ids.size
      (ids - (things.collect{|x| x.id})).collect{|missing| ids[ids.index(missing)] = nil}
      ids = ids.compact
    end

    raise &amp;quot;Out of sync! Found #{ids.size} items in index, but only #{things.size} were found in database! Remove #{(ids - (things.collect{|x| x.id})).to_sentence}.&amp;quot; unless things.size == ids.size

    things.each do |thing|
      position = ids.index(thing.id)
      ordered_things[position] = thing
    end

    ordered_things
  end
</pre>
<p>The first four lines above the &#8220;out of sync&#8221; message is what is critical.  It will attempt to remove the missing object from the items that solr will return.  If all else fails, then it will be displaying the &#8220;out of sync&#8221; error, but would still be displaying the ids that were causing the problem.</p>
<p>Its quick, but not dirty.  It works, but will not really guarantee that your problem will go away permanently.  I suggest you do a complete reindex of your whole data.  Or better yet, whatever was causing it, just make sure that there are no direct database deletion of any data so that solr will always remain in sync with your database.</p>
<p>Also there is an alternative option if you dont like the above.<br />
Why just don&#8217;t MySQL decide your ordering.</p>
<p>A small snippet you need to change in</p>
<blockquote><p>
acts_as_solr/lib/parser_methods.rb
</p></blockquote>
<pre class="brush: ruby">
 def find_objects(ids, options, configuration)
      result = if configuration[:lazy] &amp;amp;&amp;amp; configuration[:format] != :ids
        ids.collect {|id| ActsAsSolr::LazyDocument.new(id, self)}
      elsif configuration[:format] == : objects
        conditions = [ &amp;quot;#{self.table_name}.#{primary_key} in (?)&amp;quot;, ids ]
        find_options = {:conditions =&amp;gt; conditions}
        find_options[:include] = options[:include] if options[:include]
        if self.connection.adapter_name =~ /mysql/i
          find_options[:order] = &amp;quot;FIELD(#{self.table_name}.#{primary_key}, #{ids.join(&#039;,&#039;)})&amp;quot;
          result = self.find(:all, find_options)
        else
          result = reorder(self.find(:all, find_options), ids)
        end
      else
        ids
      end

      result
    end
</pre>
<p>In the above method it will check if the adapter is mysql then it will fetch the latest result list from the DB which will not cause the &#8220;Out Of Sync&#8221; issue.</p>
<p>Hope this helps.</p>
]]></content:encoded>
			<wfw:commentRss>http://blog.bhushangahire.net/2010/10/05/removing-out-of-sync-error-in-acts_as_solr/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Run acts_as_solr in JRuby in background mode</title>
		<link>http://blog.bhushangahire.net/2010/07/12/run-acts_as_solr-in-jruby-in-background-mode/?utm_source=rss&#038;utm_medium=rss&#038;utm_campaign=run-acts_as_solr-in-jruby-in-background-mode</link>
		<comments>http://blog.bhushangahire.net/2010/07/12/run-acts_as_solr-in-jruby-in-background-mode/#comments</comments>
		<pubDate>Mon, 12 Jul 2010 12:43:07 +0000</pubDate>
		<dc:creator>Bhushan G Ahire</dc:creator>
				<category><![CDATA[JRuby]]></category>
		<category><![CDATA[Rails]]></category>
		<category><![CDATA[ruby]]></category>
		<category><![CDATA[background]]></category>
		<category><![CDATA[fork]]></category>
		<category><![CDATA[solr]]></category>

		<guid isPermaLink="false">http://blog.bhushangahire.net/?p=217</guid>
		<description><![CDATA[<p class="ArticleSummary">When you try and run rake solr:start or rake solr:stop it uses Kernel.fork to spawn of a child process. However in JRuby this is disabled by default due to concurrency issues. And this prevents your solr rake tasks from running under a JRuby environment...</p>

<div class="extended">
<h3>The Problem</h3>
When you try and run rake solr:start or rake solr:stop it uses Kernel.fork to spawn of a child process.
However in JRuby this is disabled by default due to concurrency issues. There is an option to enabling fork (jruby -J-Djruby.fork.enabled=true)
within JRuby but it is experimental and as the warning says, "WARNING: fork is highly unlikely to be safe or stable on the JVM." as it can cause all sorts of weird and wonderful side-effects.
<h3>The Solution</h3>
The solution therefore is to simply alter the solr:start and solr:stop tasks to use Kernel.exec instead.
To do this find the solr rake tasks usually in {RAILS_ROOT}/vendor/acts_as_solr/lib/tasks/solr.rake. In the start task all that is required is to comment out the start of the fork block. so you only have the exec method call,
This will not start the solr process in the background. To do so you just have to add <strong>"&#38;"</strong> at the end of the exec command, which causes the jar file to run in background mode.
]]></description>
			<content:encoded><![CDATA[<p class="ArticleSummary">When you try and run rake solr:start or rake solr:stop it uses Kernel.fork to spawn of a child process. However in JRuby this is disabled by default due to concurrency issues. And this prevents your solr rake tasks from running under a JRuby environment&#8230;</p>
<div class="extended">
<h3>The Problem</h3>
<p>When you try and run rake solr:start or rake solr:stop it uses Kernel.fork to spawn of a child process.<br />
However in JRuby this is disabled by default due to concurrency issues. There is an option to enabling fork (jruby -J-Djruby.fork.enabled=true)<br />
within JRuby but it is experimental and as the warning says, &#8220;WARNING: fork is highly unlikely to be safe or stable on the JVM.&#8221; as it can cause all sorts of weird and wonderful side-effects.</p>
<h3>The Solution</h3>
<p>The solution therefore is to simply alter the solr:start and solr:stop tasks to use Kernel.exec instead.<br />
To do this find the solr rake tasks usually in {RAILS_ROOT}/vendor/acts_as_solr/lib/tasks/solr.rake. In the start task all that is required is to comment out the start of the fork block. so you only have the exec method call,<br />
This will not start the solr process in the background. To do so you just have to add <strong>&#8220;&amp;&#8221;</strong> at the end of the exec command, which causes the jar file to run in background mode.</p>
<pre class="brush: ruby">
task :start do
      require &amp;quot;#{File.dirname(__FILE__)}/../../config/solr_environment.rb&amp;quot;
      begin
        n = Net::HTTP.new(&#039;127.0.0.1&#039;, SOLR_PORT)
        n.request_head(&#039;/&#039;).value

      rescue Net::HTTPServerException #responding
        puts &amp;quot;Port #{SOLR_PORT} in use&amp;quot; and return

      rescue Errno::ECONNREFUSED #not responding
        Dir.chdir(SOLR_PATH) do
            exec &amp;quot;java #{SOLR_JVM_OPTIONS}
-Dsolr.data.dir=#{SOLR_DATA_PATH} -Djetty.logs=#{SOLR_LOGS_PATH}
-Djetty.port=#{SOLR_PORT} -jar start.jar &amp;amp;&amp;quot;
          sleep(5)
          File.open(&amp;quot;#{SOLR_PIDS_PATH}/#{ENV[&#039;RAILS_ENV&#039;]}_pid&amp;quot;, &amp;quot;w&amp;quot;){ |f| f &amp;amp;lt;&amp;amp;lt; pid}
          puts &amp;quot;#{ENV[&#039;RAILS_ENV&#039;]} Solr started successfully on #{SOLR_PORT}, pid: #{pid}.&amp;quot;
        end
      end
    end
</pre>
<p>and in the end task just comment out the begining of the fork block so you are left with</p>
<pre class="brush: ruby">
  task :stop do
    require &amp;quot;#{File.dirname(__FILE__)}/../../config/solr_environment.rb&amp;quot;
      file_path = &amp;quot;#{SOLR_PIDS_PATH}/#{ENV[&#039;RAILS_ENV&#039;]}_pid&amp;quot;
      if File.exists?(file_path)
        File.open(file_path, &amp;quot;r&amp;quot;) do |f|
          pid = f.readline
          Process.kill(&#039;TERM&#039;, pid.to_i)
        end
        File.unlink(file_path)
        Rake::Task[&amp;quot;solr:destroy_index&amp;quot;].invoke if ENV[&#039;RAILS_ENV&#039;] == &#039;test&#039;
        puts &amp;quot;Solr shutdown successfully.&amp;quot;
      else
        puts &amp;quot;PID file not found at #{file_path}. Either Solr is not running or no PID file was written.&amp;quot;
      end
  end
</pre>
<p>you should now be able to run your solr rake tasks under jruby with out any problems..</p>
</div>
]]></content:encoded>
			<wfw:commentRss>http://blog.bhushangahire.net/2010/07/12/run-acts_as_solr-in-jruby-in-background-mode/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Ruby Mixin Tutorial</title>
		<link>http://blog.bhushangahire.net/2010/06/03/ruby-mixin-tutorial/?utm_source=rss&#038;utm_medium=rss&#038;utm_campaign=ruby-mixin-tutorial</link>
		<comments>http://blog.bhushangahire.net/2010/06/03/ruby-mixin-tutorial/#comments</comments>
		<pubDate>Thu, 03 Jun 2010 05:08:28 +0000</pubDate>
		<dc:creator>Bhushan G Ahire</dc:creator>
				<category><![CDATA[ruby]]></category>
		<category><![CDATA[mixin]]></category>

		<guid isPermaLink="false">http://blog.bhushangahire.net/?p=195</guid>
		<description><![CDATA[In Java you just have classes (both abstract and concrete) and interfaces. The Ruby language provides classes, modules, and a mix of both. In this post I want to dive into mixins in Ruby. In the Ruby language a mixin is a class that is mixed with a module. In other words the implementation of [...]]]></description>
			<content:encoded><![CDATA[<p>In Java you just have classes (both abstract and concrete) and interfaces.  The Ruby language provides classes, modules, and a mix of both.  In this post I want to dive into mixins in Ruby.</p>
<p>In the Ruby language a mixin is a class that is mixed with a module.  In other words the implementation of the class and module are joined, intertwined, combined, etc.  A mixin is a different mechanism to the extend construct used to add concrete implementation to a class.  With a mixin you can extend from a module instead of a class.  Before we get started with the mixin examples let me first explain what a module is.</p>
<p>I think of a module as a degenerate abstract class.  A module can’t be instantiated and no class can directly extend it but a module can fully implement methods.  A class can leverage the implementation of a module by including the module’s methods.  A module can define methods that can be shared in different and seperate classes either at the class or instance level.</p>
<p>Let me define a module, albeit a trivial one, that would convert a numeric integer value to English.</p>
<pre class="brush: ruby">
# Convert a integer value to English.
module Stringify
  # Requires an instance variable @value
  def stringify
    if @value == 1
      &amp;amp;amp;quot;One&amp;amp;amp;quot;
    elsif @value == 2
      &amp;amp;amp;quot;Two&amp;amp;amp;quot;
    elsif @value == 3
      &amp;amp;amp;quot;Three&amp;amp;amp;quot;
    end
  end
end
</pre>
<p>Note that the Stringify module makes use of a @value instance variable.  The class that will be mixed with this module needs to define and set a @value instance variable since the Stringify module uses it but does not define it.  In addition to instance variables a module could invoke methods defined not in the module itself but in the class that it will be mixed with.</p>
<p>Now let me construct a self contained module that is not dependent on the implementation of any class that it can be mixed with.</p>
<pre class="brush: ruby">
# A Math module akin to Java Math class.
module Math
  # Could be called as a class, static, method
  def add(val_one, val_two)
    BigInteger.new(val_one + val_two)
  end
end
</pre>
<p>The methods in the Math module are intended to be invoked like class methods, also known as static methods.  The add method in the Math module accepts two integer values and returns an instance of BigInteger.  Let me now define the mixin BigInteger class.</p>
<p>[sourcecode launguage="ruby"]<br />
# Base Number class<br />
class Number<br />
  def intValue<br />
    @value<br />
  end<br />
end</p>
<p># BigInteger extends Number<br />
class BigInteger &lt; Number</p>
<p>  # Add instance methods from Stringify<br />
  include Stringify</p>
<p>  # Add class methods from Math<br />
  extend Math</p>
<p>  # Add a constructor with one parameter<br />
  def initialize(value)<br />
    @value = value<br />
  end<br />
end<br />
[/sourcecode]</p>
<p>I loosely modeled the BigInteger and Number classes after the Java versions.  The BigInteger class defines one constructor and directly inherits one method from the Number base class.  To mix in the methods implemented in the Stringify and Math modules with the BigInteger class you will note the usage of the include and extend methods, respectively.</p>
<p>[sourcecode launguage="ruby"]<br />
# Create a new object<br />
bigint1 = BigInteger.new(10)<br />
# Call a method inherited from the base class<br />
puts bigint1.intValue   # &#8211;&gt; 10<br />
[/sourcecode]</p>
<p>The extend method will mix a module’s methods at the class level.  The method defined in the Math module can be used as a class/static method.</p>
<p>[sourcecode launguage="ruby"]<br />
# Call class method extended from Math<br />
bigint2 = BigInteger.add(-2, 4)<br />
puts bigint2.intValue   # &#8211;&gt; 2<br />
[/sourcecode]</p>
<p>The include method will mix a module’s methods at the instance level, meaning that the methods will become instance methods.  The method defined in the Stringify module can be used as an instance method.</p>
<p>[sourcecode launguage="ruby"]<br />
# Call a method included from Stringify<br />
puts bigint2.stringify   # &#8211;&gt; &#8216;Two&#8217;<br />
[/sourcecode]</p>
<p>There is another use of the extend method.  You can enhance an object instance by mixing it with a module at run time!  This is a powerful  feature.  Let me create a module that will be used to extend an object, changing it’s responsibilities at runtime.</p>
<p>[sourcecode launguage="ruby"]<br />
# Format a numeric value as a currency<br />
module CurrencyFormatter<br />
  def format<br />
    &quot;$#{@value}&quot;<br />
  end<br />
end<br />
[/sourcecode]</p>
<p>To mix an object instance with a module you can do the following:</p>
<p>[sourcecode launguage="ruby"]<br />
# Add the module methods to<br />
# this object instance, only!<br />
bigint2.extend CurrencyFormatter<br />
puts bigint2.format   # &#8211;&gt; &#8216;$2&#8242;<br />
[/sourcecode]</p>
<p>Calling the extend method on an an instance will only extend that one object, objects of the same class will not be extended with the new functionality.</p>
<p>[sourcecode launguage="ruby"]<br />
puts bigint1.format   # will generate an error<br />
[/sourcecode]</p>
<p>Modules that will be mixed with a class via the include or extend method could define something like a contructor or initializer method to the module.  The module initializer method will be invoked at the time the module is mixed with a class.  When a class extends a module the module’s self.extended method will be invoked:</p>
<p>[sourcecode launguage="ruby"]<br />
module Math<br />
  def self.extended(base)<br />
    # Initialize module.<br />
  end<br />
end<br />
[/sourcecode]</p>
<p>The self prefix indicates that the method is a static module level method.  The base parameter in the static extended method will be either an instance object or class object of the class that extended the module depending whether you extend a object or class, respectively.</p>
<p>When a class includes a module the module’s self.included method will be invoked.</p>
<p>[sourcecode launguage="ruby"]<br />
module Stringify<br />
  def self.included(base)<br />
    # Initialize module.<br />
  end<br />
end<br />
[/sourcecode]</p>
<p>The base parameter will be a class object for the class that includes the module.</p>
<p>It is important to note that inside the included and extended initializer methods you can include and extend other modules, here is an example of that:</p>
<p>[sourcecode launguage="ruby"]<br />
module Stringify<br />
  def self.included(base)<br />
    base.extend SomeOtherModule<br />
  end<br />
end<br />
[/sourcecode] </p>
]]></content:encoded>
			<wfw:commentRss>http://blog.bhushangahire.net/2010/06/03/ruby-mixin-tutorial/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Paginating multiple models using will_paginate on the same page</title>
		<link>http://blog.bhushangahire.net/2010/04/13/paginating-multiple-models-using-will_paginate-on-the-same-page/?utm_source=rss&#038;utm_medium=rss&#038;utm_campaign=paginating-multiple-models-using-will_paginate-on-the-same-page</link>
		<comments>http://blog.bhushangahire.net/2010/04/13/paginating-multiple-models-using-will_paginate-on-the-same-page/#comments</comments>
		<pubDate>Tue, 13 Apr 2010 12:22:08 +0000</pubDate>
		<dc:creator>Bhushan G Ahire</dc:creator>
				<category><![CDATA[Rails]]></category>
		<category><![CDATA[ruby]]></category>
		<category><![CDATA[pagination]]></category>
		<category><![CDATA[will paginate]]></category>

		<guid isPermaLink="false">http://blog.bhushangahire.net/?p=169</guid>
		<description><![CDATA[The will_paginate plugin makes pagination for your models in Ruby on Rails ridiculously simple. However sometimes you’ll find yourself wanting to paginate over two or more models on a single page. For instance, you might want to display a list of users and administrators on a single page along with a pager for each model [...]]]></description>
			<content:encoded><![CDATA[<div class="snap_preview">
<p>The <a title="will_paginate plugin" href="http://wiki.github.com/mislav/will_paginate" target="_blank">will_paginate</a> plugin makes pagination for your models in Ruby on Rails ridiculously simple. However sometimes you’ll find yourself wanting to paginate over two or more models on a single page. For instance, you might want to display a list of users and administrators on a single page along with a pager for each model (assuming that users and administrators are stored in separate tables).</p>
<h3>Controller code</h3>
<p>The code is pretty simple, except that I am specifying the page to show to be equal to params[:user_page] and params[:administrator_page] respectively. Since we are allowing the ability to page over two models, we need two separate parameters to determine which page of users or administrators to show.</p>
<pre class="brush: js">
@users = User.paginate(:page =&amp;gt; params[:user_page], :per_page =&amp;gt; 10)&amp;lt;br/&amp;gt;
@administrators = Administrator.paginate(:page =&amp;gt; params[:administrator_page], :per_page =&amp;gt; 10)
</pre>
<h3>View code</h3>
<p>In the view all we need to do is make sure to set the param_value to the correct value to indicate to the plugin that we want to use a different parameter name for the page. The default is simply called ‘page’, but we need to make sure to use ‘user_page’ and ‘administrator_page’ instead for the two different models.</p>
<pre class="brush: js">
&amp;lt;%= will_paginate @users, :param_name =&amp;gt; &#039;user_page&#039; %&amp;gt;&amp;lt;br/&amp;gt;
&amp;lt;%= will_paginate @administrators, :param_name =&amp;gt; &#039;administrator_page&#039; %&amp;gt;
</pre>
<p>That’s it, you should now be able to page through your users and administrators on the same page.</p>
</div>
]]></content:encoded>
			<wfw:commentRss>http://blog.bhushangahire.net/2010/04/13/paginating-multiple-models-using-will_paginate-on-the-same-page/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>List of useful rake tasks for Rails&#8230;</title>
		<link>http://blog.bhushangahire.net/2010/03/25/list-of-useful-rake-tasks-for-rails/?utm_source=rss&#038;utm_medium=rss&#038;utm_campaign=list-of-useful-rake-tasks-for-rails</link>
		<comments>http://blog.bhushangahire.net/2010/03/25/list-of-useful-rake-tasks-for-rails/#comments</comments>
		<pubDate>Thu, 25 Mar 2010 12:12:11 +0000</pubDate>
		<dc:creator>Bhushan G Ahire</dc:creator>
				<category><![CDATA[Rails]]></category>
		<category><![CDATA[ruby]]></category>
		<category><![CDATA[rake]]></category>

		<guid isPermaLink="false">http://blog.bhushangahire.net/?p=159</guid>
		<description><![CDATA[rake cache:clear # Clears all cached pages rake db:bootstrap # Loads a schema.rb file into the database and then loads the initial database fixtures. rake db:bootstrap:copy_default_theme # Copy default theme to site theme rake db:migrate # Migrate the database through scripts in db/migrate. Target specific version with VERSION=x rake db:schema:dump # Create a db/schema.rb file [...]]]></description>
			<content:encoded><![CDATA[<pre>rake cache<span style="color: #aa6600;">:clear</span>
<span style="color: #888888;"># Clears all cached pages</span>
rake db<span style="color: #aa6600;">:bootstrap</span>
<span style="color: #888888;"># Loads a schema.rb file into the database and then loads the initial database fixtures.</span>
rake db<span style="color: #aa6600;">:bootstrap</span><span style="color: #aa6600;">:copy_default_theme</span>
<span style="color: #888888;"># Copy default theme to site theme</span>
rake db<span style="color: #aa6600;">:migrate</span>
<span style="color: #888888;"># Migrate the database through scripts in db/migrate. Target specific version with VERSION=x</span>
rake db<span style="color: #aa6600;">:schema</span><span style="color: #aa6600;">:dump</span>
<span style="color: #888888;"># Create a db/schema.rb file that can be portably used against any DB supported by AR</span>
rake db<span style="color: #aa6600;">:schema</span><span style="color: #aa6600;">:load</span>
<span style="color: #888888;"># Load a schema.rb file into the database
</span>rake db<span style="color: #aa6600;">:bootstrap</span><span style="color: #aa6600;">:load</span>
<span style="color: #888888;"># Load initial database fixtures (in db/bootstrap/*.yml) into the current environment's database.  Load specific fixtures using FIXTURES=x,y</span>
rake db<span style="color: #aa6600;">:fixtures</span><span style="color: #aa6600;">:load</span>
<span style="color: #888888;"># Load fixtures into the current environment's database.  Load specific fixtures using FIXTURES=x,y</span>
rake db<span style="color: #aa6600;">:sessions</span><span style="color: #aa6600;">:clear</span>
<span style="color: #888888;"># Clear the sessions table</span>
rake db<span style="color: #aa6600;">:sessions</span><span style="color: #aa6600;">:create</span>
<span style="color: #888888;"># Creates a sessions table for use with CGI::Session::ActiveRecordStore</span>
rake db<span style="color: #aa6600;">:structure</span><span style="color: #aa6600;">:dump</span>
<span style="color: #888888;"># Dump the database structure to a SQL file</span>
rake db<span style="color: #aa6600;">:test</span><span style="color: #aa6600;">:clone</span>
<span style="color: #888888;"># Recreate the test database from the current environment's database schema</span>
rake db<span style="color: #aa6600;">:test</span><span style="color: #aa6600;">:clone_structure</span>
<span style="color: #888888;"># Recreate the test databases from the development structure</span>
rake db<span style="color: #aa6600;">:test</span><span style="color: #aa6600;">:prepare</span>
<span style="color: #888888;"># Prepare the test database and load the schema</span>
rake db<span style="color: #aa6600;">:test</span><span style="color: #aa6600;">:purge</span>
<span style="color: #888888;"># Empty the test database</span>
rake deploy
<span style="color: #888888;"># Push the latest revision into production using the release manager</span>
rake diff_from_last_deploy
<span style="color: #888888;"># Describe the differences between HEAD and the last production release</span>
rake doc<span style="color: #aa6600;">:app</span>
<span style="color: #888888;"># Build the app HTML Files</span>
rake doc<span style="color: #aa6600;">:clobber_app
</span><span style="color: #888888;"># Remove rdoc products</span>
rake doc<span style="color: #aa6600;">:clobber_plugins</span>
<span style="color: #888888;"># Remove plugin documentation</span>
rake doc<span style="color: #aa6600;">:clobber_rails</span>
<span style="color: #888888;"># Remove rdoc products</span>
rake doc<span style="color: #aa6600;">:plugins</span>
<span style="color: #888888;"># Generate documation for all installed plugins</span>
rake doc<span style="color: #aa6600;">:rails</span>
<span style="color: #888888;"># Build the rails HTML Files</span>
rake doc<span style="color: #aa6600;">:reapp</span>
<span style="color: #888888;"># Force a rebuild of the RDOC files</span>
rake doc<span style="color: #aa6600;">:rerails</span>
<span style="color: #888888;"># Force a rebuild of the RDOC files</span>
rake edge
<span style="color: #888888;"># freeze rails edge</span>
rake log<span style="color: #aa6600;">:clear</span>
<span style="color: #888888;"># Truncates all *.log files in log/ to zero bytes</span>
rake rails<span style="color: #aa6600;">:freeze</span><span style="color: #aa6600;">:edge
</span><span style="color: #888888;"># Lock to latest Edge Rails or a specific revision with REVISION=X (ex: REVISION=4021) or a tag with TAG=Y (ex: TAG=rel_1-1-0)</span>
rake rails<span style="color: #aa6600;">:freeze</span><span style="color: #aa6600;">:gems</span>
<span style="color: #888888;"># Lock this application to the current gems (by unpacking them into vendor/rails)</span>
rake rails<span style="color: #aa6600;">:unfreeze</span>
<span style="color: #888888;"># Unlock this application from freeze of gems or edge and return to a fluid use of system gems</span>
rake rails<span style="color: #aa6600;">:update</span>
<span style="color: #888888;"># Update both configs, scripts and public/javascripts from Rails</span>
rake rails<span style="color: #aa6600;">:update</span><span style="color: #aa6600;">:configs</span>
<span style="color: #888888;"># Update config/boot.rb from your current rails install</span>
rake rails<span style="color: #aa6600;">:update</span><span style="color: #aa6600;">:javascripts</span>
<span style="color: #888888;"># Update your javascripts from your current rails install</span>
rake rails<span style="color: #aa6600;">:update</span><span style="color: #aa6600;">:scripts
</span><span style="color: #888888;"># Add new scripts to the application script/ directory</span>
rake remote_exec
<span style="color: #888888;"># Execute a specific action using the release manager</span>
rake rollback
<span style="color: #888888;"># Rollback to the release before the current release in production</span>
rake show_deploy_tasks
<span style="color: #888888;"># Enumerate all available deployment tasks</span>
rake stats
<span style="color: #888888;"># Report code statistics (KLOCs, etc) from the application</span>
rake test
<span style="color: #888888;"># Test all units and functionals</span>
rake test<span style="color: #aa6600;">:functionals</span>                 <span style="color: #888888;">
# Run tests for functionalsdb:test:prepare</span>
rake test<span style="color: #aa6600;">:integration</span>
<span style="color: #888888;"># Run tests for integrationdb:test:prepare</span>
rake test<span style="color: #aa6600;">:plugins</span>                     <span style="color: #888888;">
# Run tests for pluginsenvironment</span>
rake test<span style="color: #aa6600;">:recent</span>
<span style="color: #888888;"># Run tests for recentdb:test:prepare</span>
rake test<span style="color: #aa6600;">:uncommitted</span>                 <span style="color: #888888;">
# Run tests for uncommitteddb:test:prepare</span>
rake test<span style="color: #aa6600;">:units</span>
<span style="color: #888888;"># Run tests for unitsdb:test:prepare</span>
rake tmp<span style="color: #aa6600;">:cache</span><span style="color: #aa6600;">:clear</span>
<span style="color: #888888;"># Clears all files and directories in tmp/cache</span>
rake tmp<span style="color: #aa6600;">:clear</span>                        <span style="color: #888888;">
# Clear session, cache, and socket files from tmp/</span>
rake tmp<span style="color: #aa6600;">:create</span>                       <span style="color: #888888;">
# Creates tmp directories for sessions, cache, and sockets</span>
rake tmp<span style="color: #aa6600;">:pids</span><span style="color: #aa6600;">:clear</span>                   <span style="color: #888888;">
# Clears all files in tmp/pids</span>
rake tmp<span style="color: #aa6600;">:sessions</span><span style="color: #aa6600;">:clear</span>               <span style="color: #888888;">
# Clears all files in tmp/sessions</span>
rake tmp<span style="color: #aa6600;">:sockets</span><span style="color: #aa6600;">:clear</span>
<span style="color: #888888;"># Clears all files in tmp/sockets</span>
rake update_dialog_helper
<span style="color: #888888;"># Copies the latest dialog.js to the application's public directory</span></pre>
]]></content:encoded>
			<wfw:commentRss>http://blog.bhushangahire.net/2010/03/25/list-of-useful-rake-tasks-for-rails/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Setup Capistrano to deploy Rails application on Amazon EC2 with Git</title>
		<link>http://blog.bhushangahire.net/2010/02/17/setup-capistrano-to-deploy-rails-application-on-amazon-ec2-with-git/?utm_source=rss&#038;utm_medium=rss&#038;utm_campaign=setup-capistrano-to-deploy-rails-application-on-amazon-ec2-with-git</link>
		<comments>http://blog.bhushangahire.net/2010/02/17/setup-capistrano-to-deploy-rails-application-on-amazon-ec2-with-git/#comments</comments>
		<pubDate>Wed, 17 Feb 2010 06:22:49 +0000</pubDate>
		<dc:creator>Bhushan G Ahire</dc:creator>
				<category><![CDATA[capistrano]]></category>
		<category><![CDATA[git]]></category>
		<category><![CDATA[Rails]]></category>
		<category><![CDATA[ruby]]></category>
		<category><![CDATA[Security]]></category>
		<category><![CDATA[Subversion]]></category>
		<category><![CDATA[ec2]]></category>
		<category><![CDATA[server]]></category>

		<guid isPermaLink="false">http://blog.bhushangahire.net/?p=155</guid>
		<description><![CDATA[1: Create a new Rails app &#8211; we&#8217;ll call is &#8216;deploytest&#8217; $ rails deploytest $ cd deploytest 2: Create a local Git repository for it $ git init $ git add * $ git commit -a -m 'initial commit' $ git status 3: Create a couple of Capistrano files $ capify . 4: Edit config/deploy.rb [...]]]></description>
			<content:encoded><![CDATA[<div class="post-body entry-content">1: Create a new Rails app &#8211; we&#8217;ll call is &#8216;deploytest&#8217;</p>
<pre class="prettyprint"><span class="pln">$ rails deploytest
$ cd deploytest</span></pre>
<p>2: Create a local Git repository for it</p>
<pre class="prettyprint"><span class="pln">$ git init
$ git add </span><span class="pun">*</span><span class="pln">
$ git commit </span><span class="pun">-</span><span class="pln">a </span><span class="pun">-</span><span class="pln">m </span><span class="str">'initial commit'</span><span class="pln">
$ git status</span></pre>
<p>3: Create a couple of Capistrano files</p>
<pre class="prettyprint"><span class="pln">$ capify </span><span class="pun">.</span></pre>
<p>4: Edit config/deploy.rb</p>
<pre class="prettyprint"><span class="com"># The name of your app</span><span class="pln">
</span><span class="kwd">set</span><span class="pln"> </span><span class="pun">:</span><span class="pln">application</span><span class="pun">,</span><span class="pln"> </span><span class="str">"deploytest"</span><span class="pln">
</span><span class="com"># The directory on the EC2 node that will be deployed to</span><span class="pln">
</span><span class="kwd">set</span><span class="pln"> </span><span class="pun">:</span><span class="pln">deploy_to</span><span class="pun">,</span><span class="pln"> </span><span class="str">"/var/www/apps/#{application}"</span><span class="pln">
</span><span class="com"># The type of Source Code Management system you are using</span><span class="pln">
</span><span class="kwd">set</span><span class="pln"> </span><span class="pun">:</span><span class="pln">scm</span><span class="pun">,</span><span class="pln"> </span><span class="pun">:</span><span class="pln">git
</span><span class="com"># The location of the LOCAL repository relative to the current app</span><span class="pln">
</span><span class="kwd">set</span><span class="pln"> </span><span class="pun">:</span><span class="pln">repository</span><span class="pun">,</span><span class="pln">  </span><span class="str">"."</span><span class="pln">
</span><span class="com"># The way in which files will be transferred from repository to remote host</span><span class="pln">
</span><span class="com"># If you were using a hosted github repository this would be slightly different</span><span class="pln">
</span><span class="kwd">set</span><span class="pln"> </span><span class="pun">:</span><span class="pln">deploy_via</span><span class="pun">,</span><span class="pln"> </span><span class="pun">:</span><span class="pln">copy

</span><span class="com"># The address of the remote host on EC2 (the Public DNS address)</span><span class="pln">
</span><span class="kwd">set</span><span class="pln"> </span><span class="pun">:</span><span class="pln">location</span><span class="pun">,</span><span class="pln"> </span><span class="str">"ec2-xxx-xxx-xxx-xxx.compute-1.amazonaws.com"</span><span class="pln">
</span><span class="com"># setup some Capistrano roles</span><span class="pln">
role </span><span class="pun">:</span><span class="pln">app</span><span class="pun">,</span><span class="pln"> location
role </span><span class="pun">:</span><span class="pln">web</span><span class="pun">,</span><span class="pln"> location
role </span><span class="pun">:</span><span class="pln">db</span><span class="pun">,</span><span class="pln">  location</span><span class="pun">,</span><span class="pln"> </span><span class="pun">:</span><span class="pln">primary </span><span class="pun">=&gt;</span><span class="pln"> </span><span class="kwd">true</span><span class="pln">

</span><span class="com"># Set up SSH so it can connect to the EC2 node - assumes your SSH key is in ~/.ssh/id_rsa</span><span class="pln">
</span><span class="kwd">set</span><span class="pln"> </span><span class="pun">:</span><span class="pln">user</span><span class="pun">,</span><span class="pln"> </span><span class="str">"root"</span><span class="pln">
ssh_options</span><span class="pun">[:</span><span class="pln">keys</span><span class="pun">]</span><span class="pln"> </span><span class="pun">=</span><span class="pln"> </span><span class="pun">[</span><span class="typ">File</span><span class="pun">.</span><span class="pln">join</span><span class="pun">(</span><span class="pln">ENV</span><span class="pun">[</span><span class="str">"HOME"</span><span class="pun">],</span><span class="pln"> </span><span class="str">".ssh"</span><span class="pun">,</span><span class="pln"> </span><span class="str">"id_rsa"</span><span class="pun">)]</span><span class="pln">
</span></pre>
<p>The only account on a default EC2 instance is root. You probably want to create a second user that is responsible for your application.</p>
<p>5: Copy your SSH public key to your EC2 node</p>
<pre class="prettyprint"><span class="pln">$ scp </span><span class="pun">-</span><span class="pln">i </span><span class="pun">~</span><span class="str">/my-ec2-keypair ~/</span><span class="pun">.</span><span class="pln">ssh</span><span class="pun">/</span><span class="pln">id_rsa</span><span class="pun">.</span><span class="pln">pub root@ec2</span><span class="pun">-</span><span class="lit">xxx</span><span class="pun">-</span><span class="lit">xxx</span><span class="pun">-</span><span class="lit">xxx</span><span class="pun">-xxx</span><span class="lit">.compute</span><span class="pun">-</span><span class="lit">1.amazonaws</span><span class="pun">.</span><span class="pln">com</span><span class="pun">:</span><span class="str">/root/</span><span class="pun">.</span><span class="pln">ssh</span><span class="pun">/</span><span class="pln">authorized_keys2</span></pre>
<p>NOTE the filename authorized_keys2 &#8211; not authorized_keys!!</p>
<p>6: Setup the EC2 node for Capistrano deployment.<br />
From your LOCAL machine, not the EC2 node:</p>
<pre class="prettyprint"><span class="pln">$ cap deploy</span><span class="pun">:</span><span class="pln">setup</span></pre>
<p>7: Finally, deploy your application</p>
<pre class="prettyprint"><span class="pln">$ cap deploy</span></pre>
<p>You will see lots of output and with this dummy application some of those will report errors/warnings. Don&#8217;t worry about that for now.</p>
<p>8: Check that the Deployment was successful<br />
Connect to the EC2 node with SSH the regular way, cd to the app directory and check that everything is there. If that is all working then you are ready to deploy a real application and add custom tasks for managing the database, restarting the server etc.</p>
<p>Bear in mind that Capistrano add new &#8216;releases&#8217; of your software in separate directories and symlinks the &#8216;current&#8217; directory to the latest. So the root of your deployed application is the &#8216;current&#8217; subdirectory.</p>
<p>Hope this will help you setting up your ec2 instance with capistrano.</p></div>
]]></content:encoded>
			<wfw:commentRss>http://blog.bhushangahire.net/2010/02/17/setup-capistrano-to-deploy-rails-application-on-amazon-ec2-with-git/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Send SMS from Ruby On Rails application using web service, SOAP API</title>
		<link>http://blog.bhushangahire.net/2010/01/15/send-sms-from-ruby-on-rails-application-using-web-service-soap-api/?utm_source=rss&#038;utm_medium=rss&#038;utm_campaign=send-sms-from-ruby-on-rails-application-using-web-service-soap-api</link>
		<comments>http://blog.bhushangahire.net/2010/01/15/send-sms-from-ruby-on-rails-application-using-web-service-soap-api/#comments</comments>
		<pubDate>Fri, 15 Jan 2010 11:09:19 +0000</pubDate>
		<dc:creator>Bhushan G Ahire</dc:creator>
				<category><![CDATA[Rails]]></category>
		<category><![CDATA[ruby]]></category>
		<category><![CDATA[mailserve]]></category>
		<category><![CDATA[sms]]></category>
		<category><![CDATA[soap]]></category>

		<guid isPermaLink="false">http://blog.bhushangahire.net/2010/01/15/send-sms-from-ruby-on-rails-application-using-web-service-soap-api/</guid>
		<description><![CDATA[SOAP4R is a Ruby library for accessing Web Services via SOAP. Recently I had a chance to explore SOAP4R. Here&#8217;s how to get started with it. Installation Although Ruby 1.8.x comes with SOAP4R in its standard library, it is an old, buggy version. I highly recommend using the latest gem (1.5.8 as of the this [...]]]></description>
			<content:encoded><![CDATA[<p class="entry">SOAP4R is a Ruby library for accessing Web Services via SOAP. Recently I had a chance to explore SOAP4R. Here&#8217;s how to get started with it.</p>
<p class="entry"><span id="more-3"></span></p>
<h3 class="entry">Installation</h3>
<p class="entry">Although Ruby 1.8.x comes with SOAP4R in its standard library, it is an old, buggy version. I <strong>highly</strong> recommend using the latest gem (1.5.8 as of the this update). It has one dependency, httpclient.</p>
<p class="entry"><code>gem install soap4r --include-dependencies</code></p>
<h3 class="entry">Service</h3>
<p class="entry">There are many services available to send SMS but I prefer to use,</p>
<h4 class="entry">MailServe-SMS</h4>
<p class="entry"><a href="http://qlc.in/ms/overview.htm" target="_blank">MailServe-SMS</a>, text messaging service, is everything you need for fast, no-frills, no-fuss text messaging. A quick and easy way to send SMS.</p>
<p class="entry">Let’s explore these further.</p>
<h3 class="entry">Method 1: Read the WSDL at run-time</h3>
<p class="entry">&#160;</p>
<div class="entry">
<pre class="ruby"><span style="font-weight: bold; color: rgb(204,0,102)">require</span> <span style="color: rgb(153,102,0)">&quot;soap/wsdlDriver&quot;</span>
wsdl = <span style="color: rgb(153,102,0)">&quot;http://sms.qlc.co.in/smsapi.wsdl&quot;</span>
driver = <span style="font-weight: bold; color: rgb(102,102,255)">SOAP::WSDLDriverFactory</span>.<span style="color: rgb(153,0,204)">new</span><span style="font-weight: bold; color: rgb(0,102,0)">(</span>wsdl<span style="font-weight: bold; color: rgb(0,102,0)">)</span>.<span style="color: rgb(153,0,204)">create_rpc_drive</span></pre>
</div>
<p class="entry">&#160;</p>
<p class="entry">A single call to a driver factory reads the WSDL file, and creates a driver class for you to use, complete with the methods defined by the service. What if your service requires authentication? The driver inherits methods from httpclient, so you can specify its options as you would for httpclient:</p>
<p class="entry">Once driver is get initialised you need to call SMS sending API i.e. <b>SendSMSRequest</b>.</p>
<div class="entry">
<pre class="ruby">driver.<span style="color: rgb(153,0,204)">SendSMSRequest</span><span style="font-weight: bold; color: rgb(0,102,0)">(</span><span style="color: rgb(153,102,0)">&quot;username&quot;, <span style="color: rgb(153,102,0)">&quot;password&quot;</span>, <span style="color: rgb(153,102,0)">&quot;sender_no&quot;</span>, <span style="color: rgb(153,102,0)">&quot;from_no&quot;</span>, <span style="color: rgb(153,102,0)">&quot;message&quot;</span></span><span style="font-weight: bold; color: rgb(0,102,0)">)</span></pre>
</div>
<p class="entry">&#160;</p>
<p class="entry">Once This will return you response <strong>200 SMS sent successfully </strong>on success else if the information submitted was wrong then <strong>500 Information submitted was incomplete</strong>.</p>
<p class="entry">&#160;</p>
<h3 class="entry">Method 2: Generate classes from WSDL</h3>
<p class="entry">SOAP4R installs a command-line utility called &#8216;wsdl2ruby&#8217; which can generate a client or server.</p>
<p class="entry"><strong>Coming soon…..</strong></p>
]]></content:encoded>
			<wfw:commentRss>http://blog.bhushangahire.net/2010/01/15/send-sms-from-ruby-on-rails-application-using-web-service-soap-api/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Get location from IP address in Ruby On Rails for free&#8230;.</title>
		<link>http://blog.bhushangahire.net/2009/05/20/get-location-from-ip-address-in-ruby-on-rails-for-free/?utm_source=rss&#038;utm_medium=rss&#038;utm_campaign=get-location-from-ip-address-in-ruby-on-rails-for-free</link>
		<comments>http://blog.bhushangahire.net/2009/05/20/get-location-from-ip-address-in-ruby-on-rails-for-free/#comments</comments>
		<pubDate>Wed, 20 May 2009 09:42:07 +0000</pubDate>
		<dc:creator>Bhushan Ahire</dc:creator>
				<category><![CDATA[Rails]]></category>
		<category><![CDATA[ruby]]></category>
		<category><![CDATA[Security]]></category>
		<category><![CDATA[ip address]]></category>
		<category><![CDATA[location]]></category>

		<guid isPermaLink="false">http://blog.bhushangahire.net/?p=116</guid>
		<description><![CDATA[Find below the code for finding location from IP address using IP location tools. require 'net/http' require 'rexml/document' include REXML class MapsController < ApplicationController def index @location = locateIp() end def locateIp ip = request.remote_ip ips = ip.to_s url = "http://iplocationtools.com/ip_query.php?ip="+ips xml_data = Net::HTTP.get_response(URI.parse(url)).body xmldoc = REXML::Document.new(xml_data) # Now get the root element root = [...]]]></description>
			<content:encoded><![CDATA[<div class="snap_preview">
<p>Find below the code for finding location from IP address using <a href="http://www.iplocationtools.com/">IP location tools</a>.</p>
<pre>require 'net/http'
require 'rexml/document'
include REXML

class MapsController < ApplicationController
	def index
		@location = locateIp()

	end

	def locateIp
		ip = request.remote_ip
		ips = ip.to_s
		url = "http://iplocationtools.com/ip_query.php?ip="+ips

		xml_data = Net::HTTP.get_response(URI.parse(url)).body

                xmldoc = REXML::Document.new(xml_data)

		# Now get the root element
		root = xmldoc.root
		city = ""
		regionName = ""
		countryName = ""

		# This will take country name...
		xmldoc.elements.each("Response/CountryName") {
		|e| countryName << e.text
	    }

		# Now get city name...
		xmldoc.elements.each("Response/City") {
   		|e| city << e.text
	    }

		# This will take regionName...
		xmldoc.elements.each("Response/RegionName") {
   		|e| regionName << e.text
	    }

     	ipLocation = city +", "+regionName+", "+countryName

	 return ipLocation
   end #end of method locateIp

end</pre>
</div>
]]></content:encoded>
			<wfw:commentRss>http://blog.bhushangahire.net/2009/05/20/get-location-from-ip-address-in-ruby-on-rails-for-free/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Generating ZIP files via Ruby on Rails using rubyzip</title>
		<link>http://blog.bhushangahire.net/2009/03/03/generating-zip-files-via-ruby-on-rails-using-rubyzip/?utm_source=rss&#038;utm_medium=rss&#038;utm_campaign=generating-zip-files-via-ruby-on-rails-using-rubyzip</link>
		<comments>http://blog.bhushangahire.net/2009/03/03/generating-zip-files-via-ruby-on-rails-using-rubyzip/#comments</comments>
		<pubDate>Tue, 03 Mar 2009 09:33:44 +0000</pubDate>
		<dc:creator>Bhushan Ahire</dc:creator>
				<category><![CDATA[Rails]]></category>
		<category><![CDATA[ruby]]></category>
		<category><![CDATA[rubyzip]]></category>

		<guid isPermaLink="false">http://blog.bhushangahire.net/?p=65</guid>
		<description><![CDATA[gem install rubyzip Then, in the model that I’m using to generate the zip bundles, I add a couple “require” statements: require 'zip/zip' require 'zip/zipfilesystem' class Album < ActiveRecord::Base (...) end Next, I added a class method called bundle, which when called will use rubygem to generate the zip file. Note: the “permalink” attributes of [...]]]></description>
			<content:encoded><![CDATA[<div class="entry">
<pre>gem install rubyzip</pre>
<p>Then, in the model that I’m using to generate the zip bundles, I add a couple “require” statements:</p>
<pre>require 'zip/zip'
require 'zip/zipfilesystem'

class Album < ActiveRecord::Base
  (...)
end</pre>
<p>Next, I added a class method called bundle, which when called will use rubygem to generate the zip file. Note: the “permalink” attributes of Album and Artist are populated when an object of those models is created. I’m using them because it makes for nice filenames, too.</p>
<pre># create a zipped archive file of all the tracks in an album
def bundle(name = self.permalink, set = self.artist.permalink)
   bundle_filename = "#{RAILS_ROOT}/public/uploads/#{set}-#{name}.zip"

   # check to see if the file exists already, and if it does, delete it.
   if File.file?(bundle_filename)
     File.delete(bundle_filename)
   end

   # set the bundle_filename attribute of this object
   self.bundle_filename = "/uploads/#{set}-#{name}.zip"

   # open or create the zip file
   Zip::ZipFile.open(bundle_filename, Zip::ZipFile::CREATE) {
     |zipfile|
     # collect the album's tracks
     self.tracks.collect {
       |track|
         # add each track to the archive, names using the track's attributes
         zipfile.add( "#{set}/#{track.num}-#{track.filename}", "#{RAILS_ROOT}/public#{track.public_filename}")
       }
   }

   # set read permissions on the file
   File.chmod(0644, bundle_filename)

   # save the object
   self.save
end
</pre>
<p>Next I added a method in my controller:</p>
<pre>def create_bundle
   album = Album.find(params[:id])
   album.bundle
   flash[:notice] = 'Album was successfully zipped.'
   redirect_to album_url(album.artist, album)
end</pre>
<p>And edit my routes.rb accordingly:</p>
<pre>map.create_bundle 'create_bundle/:id', :controller => 'albums', :action => 'create_bundle'</pre>
<p>Now it’s just a matter of creating a link in the view for the admin to click whenever he/she wants to generate the zip file: </p>
<pre><%= link_to('Create Album Zip', create_bundle_path(@album)) %></pre>
<p>…and a link for the user to click to download the zip file if it exists:</p>
<pre><% unless @album.bundle_filename.nil? %>
<div id="grid_right">
    <%= link_to "Download Album Zip", @album.bundle_filename %>
  </div>

<% end %></pre>
<p>That’s it! Refer to the <a href="http://rubyzip.sourceforge.net/">rubyzip documentation</a> for more info.</p>
</p></div>
]]></content:encoded>
			<wfw:commentRss>http://blog.bhushangahire.net/2009/03/03/generating-zip-files-via-ruby-on-rails-using-rubyzip/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
	</channel>
</rss>

