Archive

Archive for the ‘Development’ Category

super action middleware

June 30th, 2010

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 ‘why’ 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 is only proof of concept, it was tested only using integration tests, if you ever try it more please let me know.

First Step is to create middleware scaffold ‘lib/super_action.rb’:

class SuperAction
  include Rack::Utils

  def initialize(app)
    @app = app
  end

  def call(env)
    @app.call(env)
  end
end

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 ‘config/environment.rb’:

...
require File.join(File.dirname(__FILE__), 'boot')

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, 'SuperAction'
      configuration.middleware.insert_before 'SuperAction', ActiveRecord::ConnectionAdapters::ConnectionManagement
      configuration.middleware.insert_before 'SuperAction', ActiveRecord::QueryCache
      old_load_application_classes
    end
  end
end

Rails::Initializer.run do |config|
...

We can not do the middleware changes directly in initializer using config.middleware because then it raises exception NameError on ‘ActiveRecord::QueryCache’ - it is loaded in the initialization stack after environment. So this is the current stack looks now for me:

~/projects/super_action> 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

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.

When we have correct order of middlewares now the super action functionality, back to ‘lib/super_action.rb’:

class SuperAction
  include Rack::Utils

  def initialize(app)
    @app = app
  end

  def call(env)
    uri  = env['REQUEST_URI'] || env['PATH_INFO']
    wrapper = env['rack.input']
    body = wrapper.read
    wrapper.rewind

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

    first_response = nil

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

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

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

      first_response.instance_variable_set(:@body, response_body)
      [ 200, header, response_body]
    else
      @app.call(env)
    end
  end
end

I know the code looks tricky, it realy is, but finally it allowed me to run the following test:

  test "update many books" do
    Book.delete_all

    start = Time.now

    xml = Builder::XmlMarkup.new
    xml.requests 'type' => 'array' do
      xml.request do
        xml.url '/books.xml'
        xml.method 'POST'
        xml.id 0
        xml.content_type 'application/xml'
        xml.body do
          xml.cdata! '<title>book2</title>'
        end
      end
      xml.request do
        xml.url '/books.xml'
        xml.method 'POST'
        xml.id 1
        xml.content_type 'application/xml'
        xml.body do
          xml.cdata! '<title>book3</title>'
        end
      end
      xml.request do
        xml.url '/books.xml'
        xml.method 'GET'
        xml.id 2
      end
    end

    assert_difference "Book.count", 2 do
      post '/super_action.xml', xml.target!
    end
    responses = Hash.from_xml( response.body )['responses']

    stop = Time.now
    puts "separate:#{stop-start}:"

y [ xml.target!, response.body ]

    assert_response :success
    assert_equal 3, responses.size
    responses.sort! { |a,b| a['id']  b['id'] }

    assert_equal 0, responses[0]['id']
    assert_equal 'book2', Hash.from_xml(responses[0]['body'])['book']['title']

    assert_equal 1, responses[1]['id']
    assert_equal 'book3', Hash.from_xml(responses[1]['body'])['book']['title']

    assert_equal 2, responses[2]['id']
    assert_equal 'book2', Hash.from_xml(responses[2]['body'])['books'][0]['title']
    assert_equal 'book3', Hash.from_xml(responses[2]['body'])['books'][1]['title']
  end

Speed up in integration tests is over 2x on three actions, this makes this something considerable … only if the code would be not so tricky.

Development , , , , , ,

my git prompt

May 26th, 2010

After long playing around with my prompt I finally made it stable and thought it’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>/dev/null | awk -v out=$1 -v std="dirty" '{ if ($0=="# Changes to be committed:") std = "uncommited"; last=$0 } END{ if(last!="" && last!="nothing to commit (working directory clean)") { if(out!="") print out; else print std } }')
}
function parse_git_branch {
  echo -n $(git branch --no-color 2>/dev/null | awk -v out=$1 '/^*/ { if(out=="") print $2; else print out}')
}
function parse_git_remote {
  echo -n $(git status 2>/dev/null | awk -v out=$1 '/# Your branch is / { if(out=="") print $5; else print out }')
}
export PS1='$(ppwd \l)\u@\h:\[33[33m\]\w\[33[0m\]$(parse_git_branch ":")\[33[36m\]$(parse_git_branch)\[33[0m\]$(parse_git_remote "(")\[33[35m\]$(parse_git_remote)\[33[0m\]$(parse_git_remote ")")\[33[0m\]$(parse_git_dirty  "[")\[33[31m\]$(parse_git_dirty )\[33[0m\]$(parse_git_dirty  "]")>'

I know it looks a bit complicated, unfortunately it is … this is wired bash rule that escape sequences are evaluated before evaluation of functions/variables evaluation.

Some examples of prompt using this script:

mpapis@papis:~/old_laptop/nicz-projects/content2:master> touch a
mpapis@papis:~/old_laptop/nicz-projects/content2:master[dirty]> git add .
mpapis@papis:~/old_laptop/nicz-projects/content2:master[uncommited]> git commit -m "added a file"
mpapis@papis:~/old_laptop/nicz-projects/content2:master(ahead)>git push origin master
mpapis@papis:~/old_laptop/nicz-projects/content2:master>

To make it more useful the prompt is also colored to distinguish between states of git repo.

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):

export PS1='$(git status 2>/dev/null)\[33[0m\]\n$(ppwd \l)\u@\h:\[33[33m\]\w\[33[0m\]>'

Note: download the code from here http://niczsoft.com/files/2010/05/my-git-prompt.txt

Development, Linux , ,

Deep associations in rails activerecord

May 22nd, 2010

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 => true

So the code looks now like this:

  has_many :roles,
    :readonly => true,
    :finder_sql =&gt; '
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
  '

There is one realy big downside of using finder_sql - it does not work with find_by_… or named scopes, so this forced me to continue searching and this is the result:

  def roles
    Role.scoped(
     {
       :joins => { :responsibilities => { :group => { :assigments => :user } } },
       :conditions => {"users.id" => id},
       :group => "roles.id"
     }
   )
  end

and now I can write:

user.roles.by_name(:admin).count

where by_name is an named scope

  named_scope :by_name, lambda { |type| {:conditions => [ "roles.name = ", type.to_s ] } }

Development , , , ,

rails current user

March 13th, 2010

While playing with next app I thought a bit about so common current_user … so a lot of tutorials and descriptions uses this method in application controller.

After thinking a while I found other way to do this, and for me it looks a bit better, any thoughts on it ?

So get started with User model:

class User < ActiveRecord::Base
acts_as_authentic
cattr_reader :current
end

Now in application controller add filter to set current user:

class ApplicationController < ActionController::Base
before_filter :set_user
private
def set_user
current_user_session = UserSession.find
User.send :class_variable_set, :@@current, current_user_session > current_user_session.record
end
end

Now you can use whatever you want the same method to access current user:

User.current

Added 2010.03.14 :
Warning please do not use this method it is not thread safe - it is only good for single threaded applications.

Development , ,

rails acts_as_configurable file config

March 7th, 2010

Working on my new app I thought it is necessary to get some data from configuration file, there was already plugin that had the necessary functionality - acts_as_configurable.

Unfortunately this plugin was not exactly what I was looking for It had possibility to write configuration in the class itself - I needed configuration in file.

So I did fork of the project, and now you have possibility to use rewritten version of the plugin which uses yaml file for storing configuration.

Here is example configuration file:

default:
  :first: 1st
Settings2:
  :first: 2nd
settings:
  :first: 3rd

With this configuration all the following definitions are valid:

class Settings1
  acts_as_configurable
end
class Settings2
  acts_as_configurable
end
class Settings30
  acts_as_configurable :for => 'settings'
end
class Settings31
  acts_as_configurable :for => :settings
end
class Settings4
  acts_as_configurable :for => Settings2
end
class Settings50
  acts_as_configurable 'conf'
end
class Settings51
  acts_as_configurable :conf
end
class Settings52
  acts_as_configurable :name=>'conf', :default=>'settings'
end
class Settings53
  acts_as_configurable :name=>:conf, :default=>'settings'
end
class Settings60
  acts_as_configurable :name=>'conf', :for => Settings1, :default=>'settings'
end
class Settings61
  acts_as_configurable :name=>'conf', :for => Settings1, :default=>:settings
end
class Settings7
  acts_as_configurable :name=>'conf', :for => Settings2, :default=>'settings'
end
class Settings8
  acts_as_configurable :name=>'conf1', :for => Settings1
  acts_as_configurable :name=>'conf2', :for => Settings2
end

and using following rspec code it will pass tests:

describe "ActsAsConfigurable" do
  it "should respond to 'configuration'" do
    Settings1.configuration.should_not be_nil
  end
  it "should contain default values" do
    Settings1 .configuration[:first].should eql '1st'
  end
  it "should contain values" do
    Settings2.configuration[:first].should eql "2nd"
  end
  it "should contain values for string" do
    Settings30.configuration[:first].should eql "3rd"
  end
  it "should contain values for symbol" do
    Settings31.configuration[:first].should eql "3rd"
  end
  it "should contain values for class" do
    Settings4.configuration[:first].should eql "2nd"
  end
  it "should contain values for object" do
    Settings2.new.configuration[:first].should eql "2nd"
  end
  it "should respond to 'conf' - passed as string" do
    Settings50 .conf[:first].should eql '1st'
  end
  it "should respond to 'conf' - passed as symbol" do
    Settings51 .conf[:first].should eql '1st'
  end
  it "should respond to 'conf' - passed as :name=>" do
    Settings52 .conf[:first].should eql '3rd'
  end
  it "should respond to 'conf' - passed as :name=>symbol" do
    Settings53 .conf[:first].should eql '3rd'
  end
  it "should work with other default - passed as string" do
    Settings60 .conf[:first].should eql '3rd'
  end
  it "should work with other default - passed as symbol" do
    Settings61 .conf[:first].should eql '3rd'
  end
  it "should work with other default but also exisitng for" do
    Settings7 .conf[:first].should eql '2nd'
  end
  it "should work with multiple definitions" do
    Settings8 .conf1[:first].should eql '1st'
    Settings8 .conf2[:first].should eql '2nd'
  end
end

Sources for the plugin are here http://github.com/mpapis/acts_as_configurable

Development , , ,

Get Adobe Flash playerPlugin by wpburn.com wordpress themes