Beware of Dir.mkdir Permission Handling

Took me 1 hours to figure out Dir.mkdir’s permission handling is broken ?

micha@ubuntu:/home/data/test$ ruby -e "Dir.mkdir 'wtf',0777"
micha@ubuntu:/home/data/test$ ls -al
drwxr-xr-x 2 micha   micha 4096 2008-02-24 13:07 wtf
micha@ubuntu:/home/data/test$ ruby -e "File.chmod 0777,'wtf'"
micha@ubuntu:/home/data/test$ ls -al
drwxrwxrwx 2 micha   micha 4096 2008-02-24 13:07 wtf

Dir: 0777 = drwxr-xr-x
File: 0777 = drwxrwxrwx
WTF?

And to not make it a short post, i add some recursive directory creating 😀

  #simple recursive dir creation
  FileUtils.mkdir_p dir

  #create a directory recursive and set rights/group
  def self.mkdir_r path, permission=0770,group_id=false
    path.split('/').inject(path =~ /^\// ? '/':'') do |root,part|
      path = root+'/'+part
      unless File.exist? path
        Dir.mkdir(path, permission)
        #hack, mkdir does not set the permisson right !?
        File.chmod permission,path
        File.chown(-1,group_id,path) if group_id
      end
      path
    end
  end

Escape HTML with Eclipse Monkey

Posting code on my blog became tedious.
I always had to go though and replace every < and > with > and < or some parts of the code would simply disappear! Furthermore closing square brackets seem to change normal quotes into their italic counterparts, so ] has to be replaced with &#93; too.

Eclipse Monkey to the rescue!
Since i do not want to mess up my code inside of Eclipse, i let the monkey only play with my Clipboard.

After the script was finished, it had to ‘escape’ itself to reach the public 😀

installing eclipse monkey
create a scripts folder in your project root and paste it into some escape.js, after this it should show up under ‘scripts > HTML’.

/*
 * Menu: HTML > basic html escape
 * Kudos: Michael Grosser
 * License: WTF
 */

function main() {
	systemClipboard = Packages.java.awt.Toolkit.getDefaultToolkit().getSystemClipboard();
	contents = systemClipboard.getContents(null);
	msg = contents.getTransferData(Packages.java.awt.datatransfer.DataFlavor.stringFlavor);
	msg = msg.replace('&','XXplaceHolDerXX');
	msg = msg.replace('XXplaceHolDerXX','&amp;');

	msg = msg.replace('<','&lt;');
	msg = msg.replace('>','&gt;');
	msg = msg.replace(']','&#93;');
	newContents  = new Packages.java.awt.datatransfer.StringSelection(msg);
	systemClipboard.setContents(newContents, newContents);
}

Stupid WordPress keeps ‘correcting’ my > to &gt; … :/

Validate All Models

UPDATE: Please have a look at valid_attributes

Problem: New validations vs. old data

Solution:

  • find all models
  • validate all
  • print out those that are not valid

code-base + idea

#task: rake db:validate_models
namespace :db do
  def all_models
    #get all active record classes
    Dir.glob(RAILS_ROOT + '/app/models/**/*.rb').each do |file|
      begin
        require file unless file =~ /observer/
      rescue
        #require any possible file dependencies
        if $!.to_s =~ /^uninitialized constant (\w+)$/
          require $1.underscore + '.rb'
          retry
        else
          raise
        end
      end
    end
    klasses = Object.subclasses_of(ActiveRecord::Base)
    #throw out session if it is not stored in db
    klasses.reject! do |klass|
      klass == CGI::Session::ActiveRecordStore::Session && ActionController::Base.session_store.to_s !~ /ActiveRecordStore/
    end
    klasses.select{ |c| c.base_class == c}.sort_by(&:name)
  end

  desc "Run model validations on all model records in database"
  task :validate_models => :environment do
    #validate them
    puts "-- records - model --"
    all_models.each do |klass|
      begin
        total = klass.count
      rescue
        #tableless, session...
        if $!.to_s =~ /Table .* doesn't exist/im
          puts "No Table for: #{klass}"
          next
        end
        raise
      end
      printf "%10dx %s\n", total, klass.name
      chunk_size = 1000
      (total / chunk_size + 1).times do |i|
        chunk = klass.find(:all, :offset => (i * chunk_size), :limit => chunk_size)
        chunk.reject(&:valid?).each do |record|
          puts "#{record.class}: id=#{record.id}"
          p record.errors.full_messages
          puts
        end rescue nil
      end
    end
  end
end

The Simpelest Mongrel Server (Without Rails)

I tried to make my own small server and mongrel came in handy!
Some things i covered:

  • making the server stop on ctr+c
  • ignoring favicon requests
  • using the local ip (192.168.X.X) or localhost
  • parsing the request parameters (?aaa=bbb&…) to a hash

The rest is up to you!

Stick your code into process, then run ‘ruby server.rb’ and your done 🙂

#server.rb
require 'mongrel'
require 'yaml'

module SimpleServer
  class SimpleHandler < Mongrel::HttpHandler
    def process(request, response)
      return if request.params['REQUEST_URI']=='/favicon.ico'

      params = extract_params request
      puts "Called with:"
      puts params.to_yaml

      response.start(200) do |head,out|
        head["Content-Type"] = "text/plain"
        out.write("HELLO WORLD!")
      end
    end

    def extract_params request
      params = request.params['QUERY_STRING']
      return {} if !params

      arr = params.split('&')

      hash = {}
      arr.each do |value|
        break if !value
        temp = value.split('=')
        hash[temp[0]]= temp[1]
      end 

      hash
    end
  end

  #SERVER
  def self.start
    require 'socket'
    #or use 'localhost' if u do not want to be callable from outside
    host = IPSocket.getaddress(Socket.gethostname)
    config = Mongrel::Configurator.new :host => host, :port => 3000 do
      listener {uri "/", :handler => SimpleHandler.new}
      trap("INT") { stop }
      run
    end

    #show what we are running
    puts "Running at"
    puts config.defaults.to_yaml
    config.join
  end
end

SimpleServer::start

The Color of CSS

lawngreen or 7CFC00 ?
mediumblue or 0000CD ?
Readability is increased, but you loose some fine-control and it (only?) works since  IE 6 (W3C Validator complains !?)
Its great when just building a mock-up: writing brown+olive+x is faster/easier than getting some hex values.
For professional designs, the 140 CSS Colorcodes colors are too limited, but for your everyday Webblog its ok 😉