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-10 of 15 total  RSS 

Read and Write files in Ruby

Source: Read/Write Text Files: Ruby Study Notes - Best Ruby Guide, Ruby Tutorial [dzone.com]
   1  
   2  # p027readwrite.rb  
   3  # Open and read from a text file  
   4  # Note that since a block is given, file will  
   5  # automatically be closed when the block terminates  
   6  File.open('p014constructs.rb', 'r') do |f1|  
   7   while line = f1.gets  
   8     puts line  
   9   end  
  10  end  
  11   
  12  # Create a new file and write to it  
  13  File.open('test.rb', 'w') do |f2|  
  14   # use "\n" for two lines of text  
  15   f2.puts "Created by Satish\nThank God!"  
  16  end  

Receiving REXML's *processed* children from the XPATH

This script is almost the same as 'Receiving REXML's children from the XPath' [dzone.com], however rather than pass back the whole XML node I simply wanted the node's text value. Here's how I did it:

   1  a_a = doc_a.root.elements.each('records/tag/keyword'){}.map { |node| node.text}

=> ["curtains", "in", "the", "window", "I", "said", "on", "chimney"]

see also: Modify an Array's content using map [dzone.com]

update: 5-Sep-08
Here's a similar script which creates a hash from the nodes's keyword and count elements.
   1  c_c = doc_a.root.elements.each("records/tag"){}.map { |node| 
   2    akeyword_count = Array.new
   3    akeyword_count << node.elements['keyword'].text
   4    akeyword_count << node.elements['count'].text
   5    akeyword_count
   6  }.flatten.to_h


=> {"curtains"=>"2", "window"=>"1", "in"=>"1", "the"=>"2", "chimney"=>"1", "on"=>"1", "said"=>"1", "I"=>"1"}

Note: This code implements the extended Array method 'to_h' from Convert an array to a hash [dzone.com]

J2ME - Alert Bloccante

// description of your code here

   1  
   2  import javax.microedition.lcdui.Alert;
   3  import javax.microedition.lcdui.AlertType;
   4  import javax.microedition.lcdui.Command;
   5  import javax.microedition.lcdui.CommandListener;
   6  import javax.microedition.lcdui.Displayable;
   7  
   8  public class MessageBox extends Alert implements CommandListener
   9  {
  10  	protected Chattando midlet;
  11  	
  12  	private boolean isReady = false;
  13  	
  14  	private Displayable dspBACK;
  15  	
  16  	public MessageBox(String title, String text, AlertType type, Chattando midlet)
  17  	{
  18  		super(title, text, null, type);
  19  		
  20  		this.midlet = midlet;
  21  		
  22  		this.setCommandListener(this);
  23  		this.setTimeout(Alert.FOREVER);
  24  		
  25  		// Display Precedente
  26  		dspBACK = midlet.getDisplay().getCurrent();
  27  		
  28  		// Mostra l'alert
  29  		midlet.getDisplay().setCurrent(this);
  30  		
  31  		// Attendi la conferma di chiusura
  32  		waitForDone();
  33  		
  34  		// Visualizza il precedente Display
  35  		midlet.getDisplay().setCurrent(dspBACK);
  36  	}
  37  	
  38  	private void waitForDone()
  39  	{
  40  		try
  41  		{
  42  			while(!isReady)
  43  			{
  44  				synchronized(this)
  45  				{
  46  					this.wait();
  47  					
  48  				}
  49  			}
  50  		}
  51  		catch(Exception error)
  52  		{
  53  			
  54  		}
  55  	}
  56  
  57  	public void commandAction(Command cmd, Displayable dsp)
  58  	{
  59  		if(cmd == Alert.DISMISS_COMMAND)
  60  		{
  61  			isReady = true;
  62  			
  63  			synchronized(this)
  64  			{
  65  				this.notify();
  66  			}			
  67  		}
  68  	}
  69  }

BlockFlash-Revisited.user.js

   1  
   2  // ==UserScript==
   3  // @name		BlockFlash-Revisited
   4  // @namespace		http://snippets.dzone.com/posts/show/3054
   5  // @description	Do not start Flash animation until you click on them.
   6  // @include		*
   7  // @exclude		http://www.macromedia.com/*
   8  // @exclude		http://www.atomfilms.com/*
   9  // @exclude		http://uploads.ungrounded.net/*
  10  // @exclude		http://www.albinoblacksheep.com/*
  11  // ==/UserScript==
  12  
  13  /*
  14  	Revised by Andrew Pennebaker (andrew.pennebaker@gmail.com)
  15  
  16  	Author: Jos van den Oever (jos@vandenoever.info)
  17  
  18  	License: GPL
  19  
  20  	Version history:
  21  		2006-02-12: initial version
  22  		2006-11-28: changed appearance
  23  
  24  Inspiration for this script comes from the removeFlash script and the FlashBlock firefox extension.
  25  */
  26  
  27  (function () {
  28  	var objects=document.getElementsByTagName("object");
  29  
  30  	for (i=0; i<objects.length; i++) {
  31  		var flash=objects[i];
  32  
  33  		if (flash.innerHTML.match(/.swf|shockwave|flash/)) {
  34  			var placeholder=document.createElement("div");
  35  
  36  			placeholder.style.cursor='pointer';
  37  			placeholder.style.background='orange'; // 'gray '
  38  			placeholder.style.textAlign='center';
  39  			placeholder.style.color='black';
  40  			placeholder.innerHTML="[Play Flash]";
  41  
  42  			flash.parentNode.insertBefore(placeholder, flash);
  43  			flash.on=false;
  44  
  45  			placeholder.addEventListener(
  46  				'click',
  47  				function() {
  48  					if (flash.on) {
  49  						flash.style.display='none';
  50  						placeholder.innerHTML="[Play Flash]";
  51  						flash.on=false;
  52  					}
  53  					else {
  54  						flash.style.display='';
  55  						placeholder.innerHTML="[Stop Flash]";
  56  						flash.on=true;
  57  					}
  58  				},
  59  				true
  60  			);
  61  
  62  			flash.style.display='none';
  63  		}
  64  	}
  65  })();

sparse-rec-to-fixed-block

   1  
   2  	sparse-rec-to-fixed-block: func [
   3  		rec [block!]
   4  		col-names [block!] "All column names in full schema"
   5  	][
   6  		if not all-words? col-names [alert join "sparse-rec-to-fixed-block: col-names has non-word values: " mold col-names]
   7  		collect/only val [
   8  			foreach name col-names [
   9  				val: attempt [first select/skip rec name 2]
  10  			]
  11  		]
  12  	]
  13  

SINGLE-LINE-MOLD

   1  
   2  	single-line-mold: func [
   3  	    "Reformats a block or object-spec to a single line."
   4  	    val [any-block! object!]
   5  	] [
   6  	    val: copy either any-block? val [val] [third val]
   7  	    replace/all mold new-line/all val  off  "^/" "^^/"
   8  	]

GROUP - group like elements in a block

   1  
   2      group: func [
   3          {Returns a block of sub-blocks with items partitioned by value.}
   4          block  [any-block!]
   5          /local result
   6      ][
   7          result: copy []
   8          ; First, build up a list of keys, with a place for values
   9          ; to go with each key.
  10          foreach item block [
  11              if not find/only/skip result item 2 [
  12                  repend result [item copy []]
  13              ]
  14          ]
  15          ; Add items to the block associated with each key.
  16          foreach item block [append/only select result item item]
  17          result
  18      ]

call sort with a block

From http://practicalruby.blogspot.com/2006/05/call-sort-with-block.html:

I needed to sort a list of partners today so I added:
   1  
   2  class Partner
   3    def <=>(other)
   4       self.name <=> other.name
   5    end
   6  end

However, I could have just done:
   1  
   2  Partner.find(:all).sort { |one, other| one.name <=> other.name }

Doc for sort here.

From Comments:
You could also have used sort_by as long as the target supports the spaceship operator. ie:
   1  
   2  Partner.find(:all).sort_by { |partner| partner.name }

With active_support required (or 'facet/symbol/to_proc' from the facets library) you can even:
   1  
   2  Partner.find(:all).sort_by(&:name)


Sweet.

content_tag that accepts a block = block_tag

Sometimes I want to do something like this:

   1  
   2  <% content_tag("div", :class => "section_with_error" do %>
   3    HTML GOES HERE
   4  <% end %>


instead of this:

   1  
   2  <%= content_tag("div", "HTML GOES HERE", :class => "section_with_error") %>


Put the following code in ApplicationHelper, and you can do just that (replacing "content_tag" in the example above with "block_tag", of course):

   1  
   2    def block_tag(tag, options = {}, &block)
   3      concat(content_tag(tag, capture(&block), options), block.binding)
   4    end

spec-block-to-named-block

   1  
   2  spec-block-to-named-block: func [
   3      "Change all set-words in a spec block to regular words."
   4      input [block!]
   5  ][
   6      input: copy input
   7      parse input [
   8          some [mark: set-word! any-type! (change mark to word! first mark)]
   9      ]
  10      input
  11  ]
« Newer Snippets
Older Snippets »
Showing 1-10 of 15 total  RSS