Never been to DZone Snippets before?

Snippets is a public source code repository. Easily build up your personal collection of code snippets, categorize them with tags / keywords, and share them with the world

« Newer Snippets
Older Snippets »
Showing 1-7 of 7 total  RSS 

Javascript Ajax Object

// Just a stub function we'll tell ajaxObject to call when it's done
// callback functions get responseText, and responseStat respectively
// in their arguments.
function fin(responseTxt,responseStat) {
  alert(responseStat+' - '+responseTxt);
}

// create a new ajaxObject, give it a url it will be calling and
// tell it to call the function "fin" when its got data back from the server.
var test1 = new ajaxObject('http://someurl.com/server.cgi',fin);
    test1.update();
		
// create a new ajaxObject, give it a url and tell it to call fin when it
// gets data back from the server.  When we initiate the ajax call we'll
// be passing 'id=user4379' to the server.		
var test2 = new ajaxObject('http://someurl.com/program.php',fin);
    test2.update('id=user4379');
		
// create a new ajaxObject but we'll overwrite the callback function inside
// the object to more tightly bind the object with the response hanlder.
var test3 = new ajaxObject('http://someurl.com/prog.py', fin);
    test3.callback = function (responseTxt, responseStat) {
      // we'll do something to process the data here.
      document.getElementById('someDiv').innerHTML=responseTxt;
    }
    test3.update('coolData=47&userId=user49&log=true');	
		
// create a new ajaxObject and pass the data to the server (in update) as
// a POST method instead of a GET method.
var test4 = new ajaxObject('http://someurl.com/postit.cgi', fin);
    test4.update('coolData=47&userId=user49&log=true','POST');	


function ajaxObject(url, callbackFunction) {
  var that=this;      
  this.updating = false;
  this.abort = function() {
    if (that.updating) {
      that.updating=false;
      that.AJAX.abort();
      that.AJAX=null;
    }
  }
  this.update = function(passData,postMethod) { 
    if (that.updating) { return false; }
    that.AJAX = null;                          
    if (window.XMLHttpRequest) {              
      that.AJAX=new XMLHttpRequest();              
    } else {                                  
      that.AJAX=new ActiveXObject("Microsoft.XMLHTTP");
    }                                             
    if (that.AJAX==null) {                             
      return false;                               
    } else {
      that.AJAX.onreadystatechange = function() {  
        if (that.AJAX.readyState==4) {             
          that.updating=false;                
          that.callback(that.AJAX.responseText,that.AJAX.status,that.AJAX.responseXML);        
          that.AJAX=null;                                         
        }                                                      
      }                                                        
      that.updating = new Date();                              
      if (/post/i.test(postMethod)) {
        var uri=urlCall+'?'+that.updating.getTime();
        that.AJAX.open("POST", uri, true);
        that.AJAX.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
        that.AJAX.send(passData);
      } else {
        var uri=urlCall+'?'+passData+'&timestamp='+(that.updating.getTime()); 
        that.AJAX.open("GET", uri, true);                             
        that.AJAX.send(null);                                         
      }              
      return true;                                             
    }                                                                           
  }
  var urlCall = url;        
  this.callback = callbackFunction || function () { };
}

BlankSlate: Clean an object class to its bare minimum methods in Ruby

From http://onestepback.org/index.cgi/Tech/Ruby/BlankSlate.rdoc

class BlankSlate
   instance_methods.each { |m| undef_method m unless m =~ /^__/ }
end

Lua: Descending Table Traversal Round 2: Iterator Object

This is some concept code I threw together for Lua to see how feasable it was to make a lua object/table into an iterator that you can manipulate. This iterator descends through all tables and subtables of any queued table. It returns the "path" we're at, as a string, the current table, the key, and the value.

Code:
traverse = {}
function traverse:new(tname)
	local o = {}
	o.names = {}
	o.queue = {}
	o.cur = {
		tbl = nil,
		path = nil,
		state = nil,
	}

	local mt = {}
	function mt:__call(tn)
		return o:iter(tn)
	end
	mt.__index = self
	setmetatable(o, mt)

	if tname then
		o:enqueue(tname)
	end
	return o
end
function traverse:next()
	local v
	local names, queue, cur = self.names, self.queue, self.cur

	local function _poptbl()
		if cur.tbl then
			names[cur.tbl] = nil
		end
		cur.tbl = table.remove(queue, 1)
		cur.path = names[cur.tbl]
		cur.state = nil
	end

	repeat
		-- Find something to return to the user...
		if not cur.state then
			-- Pop a new table off the stack
			_poptbl()
			if not cur.tbl then
				-- No more tables to process
				return nil
			end
		end
		cur.state,v = next(cur.tbl, cur.state)
	until cur.state

	if type(v) == "table" then
		local path = cur.path.."."..cur.state
		names[v] = path
		table.insert(queue, v)
	end
	return cur.path,cur.tbl,cur.state,v
end
function traverse:iter(tname)
	if tname then
		self:enqueue(tname)
	end
	return function(...) return self:next(unpack(arg)) end, nil, nil
end
function traverse:enqueue(tname)
	local v = _G[tname]
	table.insert(self.queue, v)
	self.names[v] = tname
end
function traverse:reset()
	self.names = {}
	self.queue = {}
end
local traverse_mt = {
    __call = function(self, tname)
             	if tname then
             		return self:new(tname):iter()
             	else
             		return self:new()
             	end
             end
}
setmetatable(traverse, traverse_mt)


Example Usage:
foo = {a={},b={},c={"bar"},d={e={},f={"moo"}},1,2,3,4,5}
bar = {"alpha", "beta", "theta", omega = {}}

local mytraverser = traverse()
mytraverser:enqueue("bar")
mytraverser:enqueue("foo")
for p,t,k,v in mytraverser() do
--for p,t,k,v in traverse('foo') do
	print(string.format("%s[%s] = %s",tostring(p),tostring(k),tostring(v)))
end


Output from Example Usage:
bar[1] = alpha
bar[2] = beta
bar[3] = theta
bar[omega] = table: 0x510650
foo[1] = 1
foo[2] = 2
foo[3] = 3
foo[4] = 4
foo[5] = 5
foo[a] = table: 0x5102d0
foo[c] = table: 0x510370
foo[b] = table: 0x510320
foo[d] = table: 0x5103c0
foo.c[1] = bar
foo.d[e] = table: 0x5104c0
foo.d[f] = table: 0x510510
foo.d.f[1] = moo

PHP5 __sleep to handle superclasses' private members

PHP5 introduces visibility for object/class methods and data members. This can prove problematic when serializing objects because base classes cannot see their parents' private vars, so these can't be serialized. Plus, a base class probably doesn't know about all of its parents' private vars (even its public and protected ones). So, I use this:


class Object {
    function __sleep() {
        return array_keys( (array)$this );
    }
}

class BaseClass extends Object {
    private $foo;
    private $dbh; // some resource, like a database handler
    function __sleep() {
        unset($this->dbh);
        return parent::__sleep();
    }
}

class SubClass extends BaseClass {
    private $bar;
    function __sleep() {
        return parent::__sleep();
    }
}



The point is, the subclasses do any local cleanup then delegate the actual __sleep request to a parent class. With a common parent class Object that all other classes extend, we can keep the real serialize code in one place but still allow children to change their state before sleeping.

Flexible Singleton

PHP function Singleton allows you holding exactly one object of a class in memory. If an object of a given class doesn't exist, Singleton will create and store a new one in static array singleton. It then (and otherwise) will return a reference to it.

Adding an optional ID allows holding more than one object a class. Assigned ID will distinguish array keys.

/**
 * Singleton Repository
 * @param string $class PHP Class Name
 * @param string $id Optional Object ID
 * @return reference Reference to existing Object
 */
function &Singleton($class, $id='') {
  static $singleton = array();
  if (!array_key_exists($class.$id, $singleton))
    $singleton[$class.$id] = &new $class();
  $reference = &$singleton[$class.$id];
  return $reference;
}


Use like this:
[edit] I'm sorry there was a mistake in the first exmaple for three days or so. Fixed.
# first call: create object
$site_user=&Singleton('Student');
$site_user->Drink_Beer(5);

# second call: get a reference
$current_user=&Singleton('Student');
echo $current_user->Show_Beers_Counter();
#will be 5

#Two different objects
$one=&Singleton('Some_Class','one');
$two=&Singleton('Some_Class','two');


Works fine with PHP4, not tested on PHP5

generic object

a generic object type thing for perl where you can use setanything and getanything to set and get properties via the AUTOLOAD method.
package thing;

use strict;

sub new {
	my %self;
	my ($class,@rest) = @_;
	unless ($#rest%2) { die "Odd parameter count\n"}
	for (my $k=0; $k<@rest; $k+=2) {
		my $wotsit = lc($rest[$k]);
		$wotsit =~ s/-//;
		$self{$wotsit} = $rest[$k+1];
		}
	bless \%self,$class;
}

sub AUTOLOAD {
        my ($where,$val) = @_;
        our $AUTOLOAD;
        $AUTOLOAD =~ s/.*://;
        my ($dirn,$what) = ($AUTOLOAD =~ /(...)(.*)/);
        if ($dirn eq "get") {
                return $$where{lc($what)};
        } elsif ($dirn eq "set") {
                $$where{lc($what)} = $val;
        }
        return 1;
}

1;



Here's a quick example of usage
use thing

$house = new thing("type","building","rooms",12,"foundations", "yes");

print $house -> gettype();
$house -> settype("tree");
print " " . $house -> gettype();

custom accessors

class Song < ActiveRecord::Base
  # Uses an integer of seconds to hold the length of the song

  def length=(minutes)
    write_attribute("length", minutes * 60)
  end

  def length
    read_attribute("length") / 60
  end
end
« Newer Snippets
Older Snippets »
Showing 1-7 of 7 total  RSS