<?xml version="1.0" encoding="UTF-8"?>
<!-- generator="wordpress/2.2.1" -->
<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/"
	>

<channel>
	<title>Circadian Rhythm</title>
	<link>http://blog.gnufied.org</link>
	<description>On Ruby and Rails</description>
	<pubDate>Thu, 30 Aug 2007 07:58:32 +0000</pubDate>
	<generator>http://wordpress.org/?v=2.2.1</generator>
	<language>en</language>
			<item>
		<title>check for user input and handle blanks</title>
		<link>http://blog.gnufied.org/2007/08/30/check-for-user-input-and-handle-blanks/</link>
		<comments>http://blog.gnufied.org/2007/08/30/check-for-user-input-and-handle-blanks/#comments</comments>
		<pubDate>Thu, 30 Aug 2007 07:57:21 +0000</pubDate>
		<dc:creator>gnufied</dc:creator>
		
		<category><![CDATA[Uncategorized]]></category>

		<guid isPermaLink="false">http://blog.gnufied.org/2007/08/30/check-for-user-input-and-handle-blanks/</guid>
		<description><![CDATA[
# If you have been programming for all these sickening years, you would have used something like this quite often.

# You are reading user input and it might be having extra spaces, newlines god knows what at the ends, so you write code like this:

foo_data = nil
t_data = nil

# your evil user may have entered [...]]]></description>
			<content:encoded><![CDATA[<pre class="code_color">
<span class="comment-delimiter"># </span><span class="comment">If you have been programming for all these sickening years, you would have used something like this quite often.
</span>
<span class="comment-delimiter"># </span><span class="comment">You are reading user input and it might be having extra spaces, newlines god knows what at the ends, so you write code like this:
</span>
foo_data = <span class="variable-name">nil</span>
t_data = <span class="variable-name">nil</span>

<span class="comment-delimiter"># </span><span class="comment">your evil user may have entered only white spaces as input so better you strip them out
</span><span class="keyword">if</span> param[<span class="constant">:from_data</span>]
  t_data = param[<span class="constant">:from_data</span>].strip
<span class="keyword">else</span>
  t_data = param[<span class="constant">:from_data</span>]
<span class="keyword">end</span>

<span class="keyword">unless</span> t_data.empty?
  foo_data = param[<span class="constant">:from_data</span>].strip
<span class="keyword">else</span>
  foo_data = <span class="string">&#8220;Some other default value you want&#8221;</span>
<span class="keyword">end</span>
<span class="comment-delimiter"># </span><span class="comment">now you can use foo_data without any fear.
</span>

<span class="comment-delimiter"># </span><span class="comment">Follows a real clean implementation of above code, checkout the number of lines reduced.
</span>
<span class="comment-delimiter"># </span><span class="comment">Lets first modify the ruby Object class system itself.
</span><span class="keyword">class</span> <span class="type">Object</span>
  <span class="keyword">def</span> <span class="function-name">nob</span>
    <span class="keyword">if</span> respond_to?(<span class="constant">:empty?</span>)
      <span class="keyword">return</span> <span class="variable-name">nil</span> <span class="keyword">if</span> empty?
      <span class="keyword">if</span> respond_to?(<span class="constant">:strip</span>)
        <span class="keyword">return</span> (strip.empty?) ? <span class="variable-name">nil</span> : (<span class="variable-name">self</span>.strip)
      <span class="keyword">end</span>
      <span class="variable-name">self</span>
    <span class="keyword">else</span>
      <span class="variable-name">self</span>
    <span class="keyword">end</span>
  <span class="keyword">end</span>
<span class="keyword">end</span>

<span class="comment-delimiter"># </span><span class="comment">Now above ruby_hack lets you write code like this:
</span>foo_data = param[<span class="constant">:from_data</span>].nob || <span class="string">&#8220;Some other default value&#8221;</span>

<span class="comment-delimiter"># </span><span class="comment">it will detect if object is a string, then before checking whether string is empty or not, it will strip the white spaces
</span><span class="comment-delimiter"># </span><span class="comment">from the string. #nob method would return nil if your object was &#8216;blank&#8217;, otherwise it will return the object itself
</span><span class="comment-delimiter"># </span><span class="comment">by blank, i mean, if its a string, it shouldn&#8217;t be nil or &#8221;   &#8221; or &#8220;n&#8221;,
</span><span class="comment-delimiter"># </span><span class="comment">by blank, i mean, not a empty array like: []
</span><span class="comment-delimiter"># </span><span class="comment">method is polymorphic in nature and operates on any ruby data type. and thats why, i put it in Object class itself.
</span>
<span class="comment-delimiter"># </span><span class="comment">But above method is slightly costlier, that your hand cranked if, elses, because it uses ruby specific facility respond_to? for
</span><span class="comment-delimiter"># </span><span class="comment">giving polymorphic behaviour and so what will you choose?
</span>
</pre>
]]></content:encoded>
			<wfw:commentRss>http://blog.gnufied.org/2007/08/30/check-for-user-input-and-handle-blanks/feed/</wfw:commentRss>
		</item>
		<item>
		<title>Ruby Hack to toggle touchpad on your notebook</title>
		<link>http://blog.gnufied.org/2007/08/14/ruby-hack-to-toggle-touchpad-on-your-notebook/</link>
		<comments>http://blog.gnufied.org/2007/08/14/ruby-hack-to-toggle-touchpad-on-your-notebook/#comments</comments>
		<pubDate>Tue, 14 Aug 2007 15:09:57 +0000</pubDate>
		<dc:creator>gnufied</dc:creator>
		
		<category><![CDATA[hardware]]></category>

		<category><![CDATA[ruby]]></category>

		<guid isPermaLink="false">http://blog.gnufied.org/2007/08/14/ruby-hack-to-toggle-touchpad-on-your-notebook/</guid>
		<description><![CDATA[Well, my Dell 1520 didn&#8217;t have a button to toggle touchpad and when you are coding your way to glory, the touchpad comes in your way and slows you down. Here is a hack, that toggles the touchpad. Save it in your ~/bin/ directory and enjoy:

#!/usr/bin/env ruby

touchpadout = `synclient -l`
touchpadout.split(&#8220;n&#8221;).each do &#124;b_output&#124;
  next unless [...]]]></description>
			<content:encoded><![CDATA[<p>Well, my Dell 1520 didn&#8217;t have a button to toggle touchpad and when you are coding your way to glory, the touchpad comes in your way and slows you down. Here is a hack, that toggles the touchpad. Save it in your ~/bin/ directory and enjoy:</p>
<pre class="code_color">
<span class="comment-delimiter">#</span><span class="comment">!/usr/bin/env ruby
</span>
touchpadout = <span class="string">`synclient -l`</span>
touchpadout.split(<span class="string">&#8220;n&#8221;</span>).each <span class="keyword">do</span> |b_output|
  <span class="keyword">next</span> <span class="keyword">unless</span> b_output =~ <span class="string">/TouchPadOff/</span>i
  key,t_value = b_output.split(<span class="string">&#8216;=&#8217;</span>)
  value = t_value.strip.to_i
  <span class="keyword">if</span> value == 0
    system(<span class="string">&#8220;synclient TouchPadOff=1&#8243;</span>)
  <span class="keyword">else</span>
    system(<span class="string">&#8220;synclient TouchPadOff=0&#8243;</span>)
  <span class="keyword">end</span>
<span class="keyword">end</span>
</pre>
]]></content:encoded>
			<wfw:commentRss>http://blog.gnufied.org/2007/08/14/ruby-hack-to-toggle-touchpad-on-your-notebook/feed/</wfw:commentRss>
		</item>
		<item>
		<title>Model hack for Sequel</title>
		<link>http://blog.gnufied.org/2007/08/13/model-hack-for-sequel/</link>
		<comments>http://blog.gnufied.org/2007/08/13/model-hack-for-sequel/#comments</comments>
		<pubDate>Mon, 13 Aug 2007 10:17:08 +0000</pubDate>
		<dc:creator>gnufied</dc:creator>
		
		<category><![CDATA[Uncategorized]]></category>

		<guid isPermaLink="false">http://blog.gnufied.org/2007/08/13/model-hack-for-sequel/</guid>
		<description><![CDATA[ Sequel is sweet. Those of us, who do not want a beast like ActiveRecord in their hair pin sized projects, its a godsend. Now, as you hack away at your application you will soon realize that, perhaps ActiveRecord models was also not bad. It gives very good code separation.
So, I wrote a stupid ugly [...]]]></description>
			<content:encoded><![CDATA[<p><a href="http://sequel.rubyforge.org/"> Sequel</a> is sweet. Those of us, who do not want a beast like ActiveRecord in their hair pin sized projects, its a godsend. Now, as you hack away at your application you will soon realize that, perhaps ActiveRecord models was also not bad. It gives very good code separation.</p>
<p>So, I wrote a stupid ugly hack that implements a model around Sequel. Now Sequel already provides one and you may ask why reinvent. It was mainly because I was bamboozled by their model implementation and couldn&#8217;t understand it mostly.</p>
<p>I have added couple of thingies to ruby core and they are neatly tucked away in a file called &#8220;ruby_hacks.rb&#8221;. Let me first show that, since its essential for our implementation:</p>
<pre>
<code>
# ruby_hacks.rb

class Hash
  def assert_valid_keys(*valid_keys)
    unknown_keys = keys - [valid_keys].flatten
    unless unknown_keys.empty?
      raise(ArgumentError, "Unknown key(s): #{unknown_keys.join(", ")}")
    end
  end
end

class Object
  def deep_copy
    Marshal.load(Marshal.dump(self))
  end

  def nothing?
    if respond_to?(:empty?) &#038;&#038; respond_to?(:strip)
      empty? or strip.empty?
    elsif respond_to?(:empty?)
      empty?
    elsif respond_to?(:zero?)
      zero?
    else
      !self
    end
  end
  def self.metaclass; class << self; self; end; end

  def self.iattr_accessor *args

    metaclass.instance_eval do
      attr_accessor *args
    end

    args.each do |attr|
      class_eval do
        define_method(attr) do
          self.class.send(attr)
        end
        define_method("#{attr}=") do |b_value|
          self.class.send("#{attr}=",b_value)
        end
      end
    end
  end
end

class Array
  def extract_options!
    last.is_a?(::Hash) ? pop : {}
  end
end
</code>
</pre>
<p>I hope above code is nothing fancy. iattr_accessor implements accessors around class instance variables.</p>
<p>Now lets implement, base class of our model, which will be inherited by all models:</p>
<pre>
<code>
# FIXME: someday it will be good to have method_missing hack, but essentianlly that would
# require some assumptions about database schema.

class DbConnection
  iattr_accessor :connection
  iattr_accessor :table_name

  VALID_FIND_OPTIONS = [:conditions, :include, :joins, :limit, :offset,:filter,:order, :select, :readonly, :group, :from, :lock ]

  def self.establish_connection(args = nil)
    options = { }
    if args.blank?
      options[:username] = ServerConfig['database']['username']
      options[:password] = ServerConfig['database']['password']
      options[:host] = ServerConfig['database']['host']
      options[:database] = ServerConfig['database']['database']
      options[:port] = ServerConfig['database']['port']
    elsif(args.is_a?(Symbol) or args.is_a? String)
      yml_string = args.to_s
      options[:username] = ServerConfig[yml_string]['username']
      options[:password] = ServerConfig[yml_string]['password']
      options[:host] = ServerConfig[yml_string]['host']
      options[:database] = ServerConfig[yml_string]['database']
      options[:port] = ServerConfig[yml_string]['port']
    end

    unless options[:port]
      @connection =
          Sequel.open("mysql://#{options[:username]}:#{options[:password]}@#{options[:host]}/#{options[:database]}")
    else
      @connection =
          Sequel.open("mysql://#{options[:username]}:#{options[:password]}@#{options[:host]}:#{options[:port]}/#{options[:database]}")
    end
  end

  establish_connection

  # if there is no connection object in current class go for parent class connection object
  def self.connection; @connection || self.superclass.connection; end

  class << self
    def set_table_name p_table_name
      @table_name = p_table_name.to_s
    end

    def execute p_sql_query
      connection.execute(p_sql_query)
    end

    def find(*args)
      options = args.extract_options!
      validate_find_options(options)
      case args.first
        when :first: find_first(options)
        when :all: find_all(options)
        else raise "Invalid find"
      end
    end

    def validate_find_options(options) #:nodoc:
      options.assert_valid_keys(VALID_FIND_OPTIONS)
    end

    def find_first(options)
      t_records = connection[table_name].filter(options[:filter]).limit(1)
      t_records[1] rescue nil
    end

    def find_all(options)
      connection[table_name].filter(options[:filter])
    end
  end

end
</code>
</pre>
<p>Now lets see couple of sample model implementations:</p>
<pre>
<code>
# user.rb
class User < DbConnection
  set_table_name :users
  def self.find_by_auth_id p_auth_id
    find(:first,:filter => { :feed_key => p_auth_id})
  end
end
</code>
</pre>
<p>Another one, where connection handler is overrideen:</p>
<pre>
<code>
class Ticker < DbConnection
  establish_connection :platform_db
  set_table_name :ubac_sym

  def self.symbol_search p_symbol
    find(:first,:filter => { :Symbol => p_symbol })
  end
end
</code>
</pre>
]]></content:encoded>
			<wfw:commentRss>http://blog.gnufied.org/2007/08/13/model-hack-for-sequel/feed/</wfw:commentRss>
		</item>
		<item>
		<title>Testing Emacs htmlize mode</title>
		<link>http://blog.gnufied.org/2007/07/19/testing-emacs-htmlize-mode/</link>
		<comments>http://blog.gnufied.org/2007/07/19/testing-emacs-htmlize-mode/#comments</comments>
		<pubDate>Thu, 19 Jul 2007 23:29:15 +0000</pubDate>
		<dc:creator>gnufied</dc:creator>
		
		<category><![CDATA[Uncategorized]]></category>

		<guid isPermaLink="false">http://blog.gnufied.org/2007/07/19/testing-emacs-htmlize-mode/</guid>
		<description><![CDATA[
    
    


    def receive_data data
      @tokenizer.extract(data).each do &#124;stock_data&#124;
        $data_log.info &#8220;&#8212;&#8212;&#8212;- #{stock_data}&#8220;
        @stock_data = UbacParser.new stock_data
        if @stock_data.valid_code?
   [...]]]></description>
			<content:encoded><![CDATA[<style type="text/css">
    <!--
      .code_color {
        color: #eeeeee;
        background-color: #102e4e;
      }
      .function-name {
        /* font-lock-function-name-face */
        color: #daa520;
        font-weight: bold;
      }
      .keyword {
        /* font-lock-keyword-face */
        color: #00bfff;
        font-weight: bold;
      }
      .string {
        /* font-lock-string-face */
        color: #deb887;
      }
      .type {
        /* font-lock-type-face */
        color: #98f5ff;
      }
      .variable-name {
        /* font-lock-variable-name-face */
        color: #4eee94;
      }</p>
<p>      a {
        color: inherit;
        background-color: inherit;
        font: inherit;
        text-decoration: inherit;
      }
      a:hover {
        text-decoration: underline;
      }
    -->
    </style>
<div class="code_color">
<pre>
    <span class="keyword">def</span> <span class="function-name">receive_data</span> data
      <span class="variable-name">@tokenizer</span>.extract(data).each <span class="keyword">do</span> |stock_data|
        <span class="variable-name">$data_log</span>.info <span class="string">&#8220;&#8212;&#8212;&#8212;- </span><span class="variable-name">#{stock_data}</span><span class="string">&#8220;</span>
        <span class="variable-name">@stock_data</span> = <span class="type">UbacParser</span>.new stock_data
        <span class="keyword">if</span> <span class="variable-name">@stock_data</span>.valid_code?
          dispatch_request
        <span class="keyword">else</span>
          send_error_without_callback <span class="string">&#8220;Invalid Protocol code&#8221;</span>
        <span class="keyword">end</span>
      <span class="keyword">end</span>
    <span class="keyword">end</span>
</pre>
</p></div>
]]></content:encoded>
			<wfw:commentRss>http://blog.gnufied.org/2007/07/19/testing-emacs-htmlize-mode/feed/</wfw:commentRss>
		</item>
		<item>
		<title>Blogging from Shire</title>
		<link>http://blog.gnufied.org/2007/07/14/blogging-from-shire/</link>
		<comments>http://blog.gnufied.org/2007/07/14/blogging-from-shire/#comments</comments>
		<pubDate>Sat, 14 Jul 2007 08:39:20 +0000</pubDate>
		<dc:creator>gnufied</dc:creator>
		
		<category><![CDATA[Uncategorized]]></category>

		<guid isPermaLink="false">http://blog.gnufied.org/2007/07/14/blogging-from-shire/</guid>
		<description><![CDATA[I am yet to decide on format of things that this new blog will contain. I am certainly not new to blogging, and have been attempting to blog for quite a while.
]]></description>
			<content:encoded><![CDATA[<p>I am yet to decide on format of things that this new blog will contain. I am certainly not new to blogging, and have been attempting to blog for quite a while.</p>
]]></content:encoded>
			<wfw:commentRss>http://blog.gnufied.org/2007/07/14/blogging-from-shire/feed/</wfw:commentRss>
		</item>
	</channel>
</rss>
