<?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/"
	>

<channel>
	<title>niczsoft</title>
	<atom:link href="http://niczsoft.com/feed/" rel="self" type="application/rss+xml" />
	<link>http://niczsoft.com</link>
	<description>{ [:consulting, :programing] =&#62; [:ruby, :rails, :linux] }</description>
	<pubDate>Wed, 30 Jun 2010 23:45:34 +0000</pubDate>
	<generator>http://wordpress.org/?v=2.7</generator>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
			<item>
		<title>super action middleware</title>
		<link>http://niczsoft.com/2010/06/super-action-middleware/</link>
		<comments>http://niczsoft.com/2010/06/super-action-middleware/#comments</comments>
		<pubDate>Wed, 30 Jun 2010 22:40:48 +0000</pubDate>
		<dc:creator>Michal Papis</dc:creator>
		
		<category><![CDATA[Development]]></category>

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

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

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

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

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

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

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

		<guid isPermaLink="false">http://niczsoft.com/?p=417</guid>
		<description><![CDATA[As a proof of concept I created an super action that allows to process more than one action at once.
Probably most of you will ask a question &#8216;why&#8217; if there is an posibility to use nested resources. Yes you can, but what if there are more different actions that do not have common root?
Code bellow [...]]]></description>
			<content:encoded><![CDATA[<div class="tweetmeme_button" style="float: right; margin-left: 10px;"><a href="http://api.tweetmeme.com/share?url=http%3A%2F%2Fniczsoft.com%2F2010%2F06%2Fsuper-action-middleware%2F" onclick="javascript:pageTracker._trackPageview('/outbound/article/api.tweetmeme.com');"><img src="http://api.tweetmeme.com/imagebutton.gif?url=http%3A%2F%2Fniczsoft.com%2F2010%2F06%2Fsuper-action-middleware%2F" height="61" width="51" /></a></div><p>As a proof of concept I created an super action that allows to process more than one action at once.<br />
Probably most of you will ask a question &#8216;why&#8217; if there is an posibility to use nested resources. Yes you can, but what if there are more different actions that do not have common root?</p>
<p>Code bellow is only proof of concept, it was tested only using integration tests, if you ever try it more please let me know.</p>
<p>First Step is to create middleware scaffold &#8216;lib/super_action.rb&#8217;:</p>
<pre class="brush: rails">
class SuperAction
  include Rack::Utils

  def initialize(app)
    @app = app
  end

  def call(env)
    @app.call(env)
  end
end
</pre>
<p>Next we have to connect it, we can not do it as advised in environment file, we also do not want to change the whole stack, the way to go is to hook into application loading process  soewhere after it initilaizes all automatic middlewares. Add the following code (module) into &#8216;config/environment.rb&#8217;:</p>
<pre class="brush: rails">
...
require File.join(File.dirname(__FILE__), &#039;boot&#039;)

module Rails
  class Initializer
    alias :old_load_application_classes :load_application_classes
    def load_application_classes
      configuration.middleware.delete ActiveRecord::QueryCache
      configuration.middleware.delete ActiveRecord::ConnectionAdapters::ConnectionManagement
      configuration.middleware.insert_before ActionController::ParamsParser, &#039;SuperAction&#039;
      configuration.middleware.insert_before &#039;SuperAction&#039;, ActiveRecord::ConnectionAdapters::ConnectionManagement
      configuration.middleware.insert_before &#039;SuperAction&#039;, ActiveRecord::QueryCache
      old_load_application_classes
    end
  end
end

Rails::Initializer.run do |config|
...
</pre>
<p>We can not do the middleware changes directly in initializer using config.middleware because then it raises exception NameError on &#8216;ActiveRecord::QueryCache&#8217; - it is loaded in the initialization stack after environment. So this is the current stack looks now for me:</p>
<pre class="brush: bash">
~/projects/super_action&gt; rake middleware
use Rack::Lock
use ActionController::Failsafe
use ActionController::Session::CookieStore, #
use ActiveRecord::ConnectionAdapters::ConnectionManagement
use ActiveRecord::QueryCache
use SuperAction
use ActionController::ParamsParser
use Rack::MethodOverride
use Rack::Head
use ActionController::StringCoercion
run ActionController::Dispatcher.new
</pre>
<p>Important here was to be before ActionController::ParamsParser, because it is responsible for providing correct params to action. Putting ConnectionManagement and QueryCache before super action should be considered as an optimization.</p>
<p>When we have correct order of middlewares now the super action functionality, back to &#8216;lib/super_action.rb&#8217;:</p>
<pre class="brush: rails">
class SuperAction
  include Rack::Utils

  def initialize(app)
    @app = app
  end

  def call(env)
    uri  = env[&#039;REQUEST_URI&#039;] || env[&#039;PATH_INFO&#039;]
    wrapper = env[&#039;rack.input&#039;]
    body = wrapper.read
    wrapper.rewind

    unless body.blank?
      params, format = if uri == &#039;/super_action.xml&#039;
        [Hash.from_xml(body), :xml]
      end
    end

    first_response = nil

    if params
      response_array = params[&#039;requests&#039;].map do |req|
        req_env = env.clone
        req_env[&#039;PATH_INFO&#039;]      = req[&#039;url&#039;]
        req_env[&#039;REQUEST_URI&#039;]    = req[&#039;url&#039;]
        req_env[&#039;REQUEST_METHOD&#039;] = req[&#039;method&#039;]
        req_env[&#039;CONTENT_TYPE&#039;]   = req[&#039;content_type&#039;]
        req_env[&#039;rack.input&#039;]     = Rack::Lint::InputWrapper.new StringIO.new( req[&#039;body&#039;] || &#039;&#039; )
        status, headers, req_response = @app.call(req_env)
        first_response ||= req_response
{
  :url =&gt; req[&#039;url&#039;],
  :method =&gt; req[&#039;method&#039;],
  :status =&gt; status,
  :body =&gt; req_response.body,
  :id =&gt; req[&#039;id&#039;]
}
      end

      response_body = case format
      when :xml then
        xml = Builder::XmlMarkup.new
        xml.responses &#039;type&#039; =&gt; &#039;array&#039; do
          response_array.each do |resp|
            xml.response do
              xml.url resp[:url]
              xml.method resp[:method]
              xml.id resp[:id], &#039;type&#039; =&gt; &#039;integer&#039;
              xml.body do
                xml.cdata! resp[:body]
              end
            end
          end
        end
      end

      header = HeaderHash.new
      header[&#039;Content-Type&#039;] = &#039;application/xml; charset=utf-8&#039;
      header[&#039;Content-Length&#039;] = response_body.size.to_s
      header[&#039;Cache-Control&#039;] = &#039;private, max-age=0, must-revalidate&#039;

      first_response.instance_variable_set(:@body, response_body)
      [ 200, header, response_body]
    else
      @app.call(env)
    end
  end
end
</pre>
<p>I know the code looks tricky, it realy is, but finally it allowed me to run the following test:</p>
<pre class="brush: rails">
  test &quot;update many books&quot; do
    Book.delete_all

    start = Time.now

    xml = Builder::XmlMarkup.new
    xml.requests &#039;type&#039; =&gt; &#039;array&#039; do
      xml.request do
        xml.url &#039;/books.xml&#039;
        xml.method &#039;POST&#039;
        xml.id 0
        xml.content_type &#039;application/xml&#039;
        xml.body do
          xml.cdata! &#039;&lt;title&gt;book2&lt;/title&gt;&#039;
        end
      end
      xml.request do
        xml.url &#039;/books.xml&#039;
        xml.method &#039;POST&#039;
        xml.id 1
        xml.content_type &#039;application/xml&#039;
        xml.body do
          xml.cdata! &#039;&lt;title&gt;book3&lt;/title&gt;&#039;
        end
      end
      xml.request do
        xml.url &#039;/books.xml&#039;
        xml.method &#039;GET&#039;
        xml.id 2
      end
    end

    assert_difference &quot;Book.count&quot;, 2 do
      post &#039;/super_action.xml&#039;, xml.target!
    end
    responses = Hash.from_xml( response.body )[&#039;responses&#039;]

    stop = Time.now
    puts &quot;separate:#{stop-start}:&quot;

y [ xml.target!, response.body ]

    assert_response :success
    assert_equal 3, responses.size
    responses.sort! { |a,b| a[&#039;id&#039;]  b[&#039;id&#039;] }

    assert_equal 0, responses[0][&#039;id&#039;]
    assert_equal &#039;book2&#039;, Hash.from_xml(responses[0][&#039;body&#039;])[&#039;book&#039;][&#039;title&#039;]

    assert_equal 1, responses[1][&#039;id&#039;]
    assert_equal &#039;book3&#039;, Hash.from_xml(responses[1][&#039;body&#039;])[&#039;book&#039;][&#039;title&#039;]

    assert_equal 2, responses[2][&#039;id&#039;]
    assert_equal &#039;book2&#039;, Hash.from_xml(responses[2][&#039;body&#039;])[&#039;books&#039;][0][&#039;title&#039;]
    assert_equal &#039;book3&#039;, Hash.from_xml(responses[2][&#039;body&#039;])[&#039;books&#039;][1][&#039;title&#039;]
  end
</pre>
<p>Speed up in integration tests is over 2x on three actions, this makes this something considerable &#8230; only if the code would be not so tricky.</p>
]]></content:encoded>
			<wfw:commentRss>http://niczsoft.com/2010/06/super-action-middleware/feed/</wfw:commentRss>
		</item>
		<item>
		<title>linux simple router</title>
		<link>http://niczsoft.com/2010/06/linux-simple-router/</link>
		<comments>http://niczsoft.com/2010/06/linux-simple-router/#comments</comments>
		<pubDate>Wed, 16 Jun 2010 21:32:21 +0000</pubDate>
		<dc:creator>Michal Papis</dc:creator>
		
		<category><![CDATA[Linux]]></category>

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

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

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

		<guid isPermaLink="false">http://niczsoft.com/?p=410</guid>
		<description><![CDATA[Had you ever need of simple routing, like sharing your connection to other computer?
I had :) so here is a script which turns my laptop into a router, simple configuration, one command, to run it save the script as router.sh

#!/bin/bash

#configuration
IF_LOC=eth0
IP_LOC=192.168.67
IF_NET=wlan0

#script
IF_NET=$(ifconfig $IF_NET &#124; awk &#039;/inet/ {print $2}&#039; &#124; grep -o &#039;[0-9]*\.[0-9]*\.[0-9]*&#039;)

#connect
iptables-save &#62; /dev/shm/old_routes
ifconfig $IF_LOC inet $IP_LOC.1
ip [...]]]></description>
			<content:encoded><![CDATA[<div class="tweetmeme_button" style="float: right; margin-left: 10px;"><a href="http://api.tweetmeme.com/share?url=http%3A%2F%2Fniczsoft.com%2F2010%2F06%2Flinux-simple-router%2F" onclick="javascript:pageTracker._trackPageview('/outbound/article/api.tweetmeme.com');"><img src="http://api.tweetmeme.com/imagebutton.gif?url=http%3A%2F%2Fniczsoft.com%2F2010%2F06%2Flinux-simple-router%2F" height="61" width="51" /></a></div><p>Had you ever need of simple routing, like sharing your connection to other computer?</p>
<p>I had :) so here is a script which turns my laptop into a router, simple configuration, one command, to run it save the script as router.sh</p>
<pre class="brush: bash">
#!/bin/bash

#configuration
IF_LOC=eth0
IP_LOC=192.168.67
IF_NET=wlan0

#script
IF_NET=$(ifconfig $IF_NET | awk &#039;/inet/ {print $2}&#039; | grep -o &#039;[0-9]*\.[0-9]*\.[0-9]*&#039;)

#connect
iptables-save &gt; /dev/shm/old_routes
ifconfig $IF_LOC inet $IP_LOC.1
ip route add $IP_LOC.0/24 dev $IF_LOC src $IP_LOC.1
iptables -t nat -A POSTROUTING -s $IF_NET.0/24 -j MASQUERADE

if ip route | grep $IP_LOC.1 &gt;/dev/null
then
  #message
  clear
  echo &quot;Enter this information in connected machines:&quot;
  echo &quot;IP address : $IP_LOC.2-254&quot;
  echo &quot;Netmask    : 255.255.255.0&quot;
  echo &quot;Gateway    : $IP_LOC.1&quot;
  echo &quot;DNS        : $(echo -n $(awk &#039;/^nameserver/ {print $2}&#039; /etc/resolv.conf))&quot;
  echo &quot;&quot;
  echo &quot;Press ENTER to continue.&quot;
  read

  #monitor connection
  iftop -i $IF_LOC

else
  echo &quot;Error setting up network&quot;
fi

#disconnect
ip route del $IP_LOC.0/24 dev $IF_LOC
ifconfig $IF_LOC down
iptables-restore &lt; /dev/shm/old_routes
rm /dev/shm/old_routes

#end
</pre>
<p>and give execute rights to the script:</p>
<pre class="brush: bash">
chmod +x router.sh
</pre>
<p>now just run it:</p>
<pre class="brush: bash">
sudo ./router.sh
</pre>
<p>Script will show configuration of new created network </p>
<pre class="brush: bash">
Enter this information in connected machines:
IP address : 192.168.67.2-254
Netmask    : 255.255.255.0
Gateway    : 192.168.67.1
DNS        : 217.172.224.160 89.228.6.21

Press ENTER to continue.
</pre>
<p>and start monitor its traffic, to quit routing hit q or CTRL+C</p>
<p>It is simplest way to start sharing internet I know off</p>
]]></content:encoded>
			<wfw:commentRss>http://niczsoft.com/2010/06/linux-simple-router/feed/</wfw:commentRss>
		</item>
		<item>
		<title>my git prompt</title>
		<link>http://niczsoft.com/2010/05/my-git-prompt/</link>
		<comments>http://niczsoft.com/2010/05/my-git-prompt/#comments</comments>
		<pubDate>Wed, 26 May 2010 21:48:33 +0000</pubDate>
		<dc:creator>Michal Papis</dc:creator>
		
		<category><![CDATA[Development]]></category>

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

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

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

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

		<guid isPermaLink="false">http://niczsoft.com/?p=401</guid>
		<description><![CDATA[After long playing around with my prompt I finally made it stable and thought it&#8217;s time to share :)
So edit your ~/.bashrc file and add following lines on the end:

shopt -s promptvars dotglob histappend no_empty_cmd_completion cdspell xpg_echo

function parse_git_dirty {
  echo -n $(git status 2&#62;/dev/null &#124; awk -v out=$1 -v std=&#34;dirty&#34; &#039;{ if ($0==&#34;# Changes [...]]]></description>
			<content:encoded><![CDATA[<div class="tweetmeme_button" style="float: right; margin-left: 10px;"><a href="http://api.tweetmeme.com/share?url=http%3A%2F%2Fniczsoft.com%2F2010%2F05%2Fmy-git-prompt%2F" onclick="javascript:pageTracker._trackPageview('/outbound/article/api.tweetmeme.com');"><img src="http://api.tweetmeme.com/imagebutton.gif?url=http%3A%2F%2Fniczsoft.com%2F2010%2F05%2Fmy-git-prompt%2F" height="61" width="51" /></a></div><p>After long playing around with my prompt I finally made it stable and thought it&#8217;s time to share :)</p>
<p>So edit your ~/.bashrc file and add following lines on the end:</p>
<pre class="brush: bash">
shopt -s promptvars dotglob histappend no_empty_cmd_completion cdspell xpg_echo

function parse_git_dirty {
  echo -n $(git status 2&gt;/dev/null | awk -v out=$1 -v std=&quot;dirty&quot; &#039;{ if ($0==&quot;# Changes to be committed:&quot;) std = &quot;uncommited&quot;; last=$0 } END{ if(last!=&quot;&quot; &amp;&amp; last!=&quot;nothing to commit (working directory clean)&quot;) { if(out!=&quot;&quot;) print out; else print std } }&#039;)
}
function parse_git_branch {
  echo -n $(git branch --no-color 2&gt;/dev/null | awk -v out=$1 &#039;/^*/ { if(out==&quot;&quot;) print $2; else print out}&#039;)
}
function parse_git_remote {
  echo -n $(git status 2&gt;/dev/null | awk -v out=$1 &#039;/# Your branch is / { if(out==&quot;&quot;) print $5; else print out }&#039;)
}
export PS1=&#039;$(ppwd \l)\u@\h:\[33[33m\]\w\[33[0m\]$(parse_git_branch &quot;:&quot;)\[33[36m\]$(parse_git_branch)\[33[0m\]$(parse_git_remote &quot;(&quot;)\[33[35m\]$(parse_git_remote)\[33[0m\]$(parse_git_remote &quot;)&quot;)\[33[0m\]$(parse_git_dirty  &quot;[&quot;)\[33[31m\]$(parse_git_dirty )\[33[0m\]$(parse_git_dirty  &quot;]&quot;)&gt;&#039;
</pre>
<p>I know it looks a bit complicated, unfortunately it is &#8230; this is wired bash rule that escape sequences are evaluated before evaluation of functions/variables evaluation.</p>
<p>Some examples of prompt using this script:</p>
<pre class="brush: bash">
mpapis@papis:~/old_laptop/nicz-projects/content2:master&gt; touch a
mpapis@papis:~/old_laptop/nicz-projects/content2:master[dirty]&gt; git add .
mpapis@papis:~/old_laptop/nicz-projects/content2:master[uncommited]&gt; git commit -m &quot;added a file&quot;
mpapis@papis:~/old_laptop/nicz-projects/content2:master(ahead)&gt;git push origin master
mpapis@papis:~/old_laptop/nicz-projects/content2:master&gt;
</pre>
<p>To make it more useful the prompt is also colored to distinguish between states of git repo.</p>
<p>For lazy users the script could be also replaced by very easy version, which prints git status before each prompt line (only where git is applicable):</p>
<pre class="brush: bash">
export PS1=&#039;$(git status 2&gt;/dev/null)\[33[0m\]\n$(ppwd \l)\u@\h:\[33[33m\]\w\[33[0m\]&gt;&#039;
</pre>
<p>Note: download the code from here <a href="http://niczsoft.com/files/2010/05/my-git-prompt.txt" >http://niczsoft.com/files/2010/05/my-git-prompt.txt</a></p>
]]></content:encoded>
			<wfw:commentRss>http://niczsoft.com/2010/05/my-git-prompt/feed/</wfw:commentRss>
		</item>
		<item>
		<title>Deep associations in rails activerecord</title>
		<link>http://niczsoft.com/2010/05/deep-associations-in-rails-activerecord/</link>
		<comments>http://niczsoft.com/2010/05/deep-associations-in-rails-activerecord/#comments</comments>
		<pubDate>Sat, 22 May 2010 21:53:08 +0000</pubDate>
		<dc:creator>Michal Papis</dc:creator>
		
		<category><![CDATA[Development]]></category>

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

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

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

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

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

		<guid isPermaLink="false">http://niczsoft.com/?p=394</guid>
		<description><![CDATA[Some time ago I wrote about complex associations, now time to add another method and corrections.
First the finder_by_sql, in that particular case It was necessary to add
:readonly =&#62; true
So the code looks now like this:

  has_many :roles,
    :readonly =&#62; true,
    :finder_sql =&#38;gt; &#039;
SELECT roles.name FROM roles
INNER JOIN responsibilities [...]]]></description>
			<content:encoded><![CDATA[<div class="tweetmeme_button" style="float: right; margin-left: 10px;"><a href="http://api.tweetmeme.com/share?url=http%3A%2F%2Fniczsoft.com%2F2010%2F05%2Fdeep-associations-in-rails-activerecord%2F" onclick="javascript:pageTracker._trackPageview('/outbound/article/api.tweetmeme.com');"><img src="http://api.tweetmeme.com/imagebutton.gif?url=http%3A%2F%2Fniczsoft.com%2F2010%2F05%2Fdeep-associations-in-rails-activerecord%2F" height="61" width="51" /></a></div><p>Some time ago I wrote about complex associations, now time to add another method and corrections.</p>
<p>First the finder_by_sql, in that particular case It was necessary to add</p>
<pre class="brush: rails">:readonly =&gt; true</pre>
<p>So the code looks now like this:</p>
<pre class="brush: rails">
  has_many :roles,
    :readonly =&gt; true,
    :finder_sql =&amp;gt; &#039;
SELECT roles.name FROM roles
INNER JOIN responsibilities ON roles.id = responsibilities.role_id
INNER JOIN assigments ON responsibilities.group_id = assigments.group_id
WHERE assigments.user_id = #{id}
GROUP BY roles.id
  &#039;
</pre>
<p>There is one realy big downside of using finder_sql - it does not work with find_by_&#8230; or named scopes, so this forced me to continue searching and this is the result:</p>
<pre class="brush: rails">
  def roles
    Role.scoped(
     {
       :joins =&gt; { :responsibilities =&gt; { :group =&gt; { :assigments =&gt; :user } } },
       :conditions =&gt; {&quot;users.id&quot; =&gt; id},
       :group =&gt; &quot;roles.id&quot;
     }
   )
  end
</pre>
<p>and now I can write:</p>
<pre class="brush: rails">user.roles.by_name(:admin).count</pre>
<p>where by_name is an named scope</p>
<pre class="brush: rails">
  named_scope :by_name, lambda { |type| {:conditions =&gt; [ &quot;roles.name = &quot;, type.to_s ] } }
</pre>
]]></content:encoded>
			<wfw:commentRss>http://niczsoft.com/2010/05/deep-associations-in-rails-activerecord/feed/</wfw:commentRss>
		</item>
		<item>
		<title>tuna salad</title>
		<link>http://niczsoft.com/2010/03/tuna-salad/</link>
		<comments>http://niczsoft.com/2010/03/tuna-salad/#comments</comments>
		<pubDate>Mon, 15 Mar 2010 21:17:46 +0000</pubDate>
		<dc:creator>Michal Papis</dc:creator>
		
		<category><![CDATA[Food]]></category>

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

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

		<guid isPermaLink="false">http://niczsoft.com/?p=380</guid>
		<description><![CDATA[make a great tuna salad with onion, tomato, soured cucumber and yogurt]]></description>
			<content:encoded><![CDATA[<div class="tweetmeme_button" style="float: right; margin-left: 10px;"><a href="http://api.tweetmeme.com/share?url=http%3A%2F%2Fniczsoft.com%2F2010%2F03%2Ftuna-salad%2F" onclick="javascript:pageTracker._trackPageview('/outbound/article/api.tweetmeme.com');"><img src="http://api.tweetmeme.com/imagebutton.gif?url=http%3A%2F%2Fniczsoft.com%2F2010%2F03%2Ftuna-salad%2F" height="61" width="51" /></a></div><p>components:<br />
5 leaves of lettuce<br />
small onion<br />
tomato<br />
soured cucumber<br />
can of tuna in oil (200g)<br />
100-150ml of yogurt<br />
to taste salt and pepper</p>
<p>preparation:<br />
- wash lettuce and cut into small strips/squares<br />
- cover the salad with finely chopped onion<br />
- sprinkle onion with salt (quite a lot) and a bit of pepper<br />
- then successively chop tomato and cucumber and arrange next layers<br />
- at the end drain tuna of the oil, and gently disintegrating arrange the last layer<br />
- cover everything with yogurt and at the end &#8230; mix everything :D</p>
<p>alternatively instead of using a lot of salt on each layer you could use a bit of salt on each layer separately those avoiding mixing.</p>
]]></content:encoded>
			<wfw:commentRss>http://niczsoft.com/2010/03/tuna-salad/feed/</wfw:commentRss>
		</item>
	</channel>
</rss>
