DZone 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
  • submit to reddit

Ruby Snippets

  • service
  • screenshots
  • Ruby
  • gem
  • free
                        require 'grabzitclient'
     
    grabzItClient = GrabzItClient.new("YOUR APPLICATION KEY", "YOUR APPLICATION SECRET")
    grabzItClient.save_picture("http://www.google.com", "images/test.jpg")                
  • symbol
  • Ruby
  • String
  • hash
                    Code for converting all keys in a multidimensional Hash.
Works non-recursive, which should give better performance.

<code>
class Hash
    def stringify_keys_deep
        superhash = {0=>self}
        hashes = [[superhash,0]]
        while not hashes.empty?
            outer_hash, outer_key = hashes.pop
            outer_hash[outer_key] = outer_hash[outer_key].inject({}) do |hash, (key, value)|
                key = key.to_s
                hash[key] = value
                hashes << [hash,key] if value.kind_of? Hash
                hash
            end
        end
        superhash[0]
    end
    def stringify_keys_deep!
        self.replace(self.stringify_keys_recursive)
    end
    
    def symbolize_keys_deep
        superhash = {0=>self}
        hashes = [[superhash,0]]
        while not hashes.empty?
            outer_hash, outer_key = hashes.pop
            outer_hash[outer_key] = outer_hash[outer_key].inject({}) do |hash, (key, value)|
                key = key.to_sym rescue key || key
                hash[key] = value
                hashes << [hash,key] if value.kind_of? Hash
                hash
            end
        end
        superhash[0]
    end
    def symbolize_keys_deep!
        self.replace(self.symbolize_keys_recursive)
    end
end
</code>                
  • arrays
  • Ruby
                    // Iterate two arrays simultaneously in Ruby

<code>
array1.zip(array2).each do |v1, v2|
  # iterates over array1 and array2
end
</code>                
  • Ruby
  • drugs
  • Beer
                    def bottle(x)
  case x
  when 0 then "no more bottles"
  when 1 then "1 bottle"
  else        "#{x} bottles"
  end + " of beer"
end

99.downto(1) do |i|
  puts <<T
#{bottle(i)} on the wall, #{bottle(i)},
take one down, pass it around,
#{bottle(i - 1)} on the wall.\n
T
end
                
  • Ruby
  • log
                    Optimize openning file trace for log:

<code>
$logq   = Queue.new
$log_fn = "/tmp/trace.log"
def log(*res) 
  mess= "%s | %s" % [Time.now.strftime("%Y-%m-%d %H:%M:%S"),res.join(" ")]
  $logq.push(mess) if $logq.size<10000
end
Thread.new do
  loop do
     sleep 10
     File.open($log_fn,"a") { |f| f.puts( $logq.pop) while $logq.size>0 } if $logq.size>0
  end
end
</code>

Or this one is perhaps better :

<code>
Thread.new do
  loop do
     m=$logq.pop
     sleep 3
     File.open($log_fn,"a") { |f| 
		f.puts( m)
		f.puts( $logq.pop) while $logq.size>0 
	 } if m
  end
end
</code>

And then, for good exit:

<code>
$th=Thread.new ...
at_exit { 
   $th.kill rescue nil
   logger("exit")
   File.open($log_fn,"a") { |f| f.puts( $logq.pop) while $logq.size>0 } if $logq.size>0
}
</code>

                
  • math
  • Ruby
                    // Calculates the Euclidean distance between two vectors (arrays) in Ruby

<code>
def euclidean_distance(vector1, vector2)
  sum = 0
  vector1.zip(vector2).each do |v1, v2|
    component = (v1 - v2)**2
    sum += component
  end
  Math.sqrt(sum)
end
</code>                
  • Heroku
  • Ruby
  • Redis
  • Ruby-on-Rails
                    You can use the following for a "it just works" approach to using REDIS in rails

First - install redis
<code>
brew install redis
</code>

Second - create the following.  Note port can be anything you want but they should be unique.  Redis by default runs on 6381 but, using that it risky, if some other app is using that you could get confusing results when keys overlap.

config/redis/development.conf
<code>
daemonize yes
port 6390
logfile ./log/redis_development.log
dbfilename ./db/development.rdb
</code>

and config/redis/test.conf

<code>
daemonize yes
port 6391
logfile ./log/redis_test.log
dbfilename ./db/test.rdb
</code>

Third - add this init script
config/init/redis_init.rb
<code>
require "redis"
rx = /port.(\d+)/
s = File.read("#{::Rails.root}/config/redis/#{::Rails.env}.conf")
port = rx.match(s)[1]
`redis-server #{::Rails.root}/config/redis/#{::Rails.env}.conf`
res = `ps aux | grep redis-server`
raise "Couldn't start redis" unless res.include?("redis-server") && res.include?("#{::Rails.root}/config/redis/#{::Rails.env}.conf")
REDIS = Redis.new(:port => port)
</code>

If you're deploying to Heroku and using redis-to-go use this script
config/init/redis_init.rb
<code>

require "redis"

if ::Rails.env == "production"
  uri = URI.parse(ENV["REDISTOGO_URL"])
  REDIS = Redis.new(:host => uri.host, :port => uri.port, :password => uri.password)
else
  rx = /port.(\d+)/
  s = File.read("#{::Rails.root}/config/redis/#{::Rails.env}.conf")
  port = rx.match(s)[1]
  `redis-server #{::Rails.root}/config/redis/#{::Rails.env}.conf`
  res = `ps aux | grep redis-server`
  raise "Couldn't start redis" unless res.include?("redis-server") && res.include?("#{::Rails.root}/config/redis/#{::Rails.env}.conf")
  REDIS = Redis.new(:port => port)
end
</config>

Then - in your app just use the REDIS constant to deal with redis.... example:
<code>
REDIS.keys
</code>
                
  • base64
  • shoes
  • Ruby
                    When we create a simple script with gui, it should be nice to puts the icons in the source script,
so whe can diffuse the code without any packaging.

This code create a ruby source which declare some file-content coded in ASCII/.base64
In the source, he put get_icon_filename(name) which put content to a temporary file and return
the filename created :

<code>
# usage: ruby gene.rb ../angel.png  face_crying.png face_smile_big.png > icons64.rb
require 'base64'
require 'tmpdir'

str=<<EEND
require 'base64'
require 'tmpdir'
$icons={}
EEND

lvar=[]
ARGV.each { |fn|
 varname=File.basename(fn).split('.')[0].gsub(/[^a-zA-Z0-9]+/,"_").downcase
 File.open(fn,"rb") { |f|   
     str+= "\n$icons['#{varname}']=<<EEND\n"+Base64.encode64(f.read)+"EEND\n" }
     lvar << varname
}
str+=<<'EEND'

def get_icon_filename(name)
  raise("icon '#{name}' unknown in #{$icons.keys}") unless $icons[name]
  fname=File.join(Dir.tmpdir,name+".png")
  puts "#{name} ==> #{fname} / #{$icons[name].size}" if $DEBUG
  File.open(fname,"wb") { |f| f.write($icons[name].unpack('m')) } unless File.exists?(fname)
  fname
end
EEND

puts str

STDERR.puts "#{lvar.join(", ")} done size=#{str.size}."
</code>

This generate a code like :
<code>
require 'base64'
require 'tmpdir'
$icons={}

$icons['angel']=<<EEND
iVBORw0KGgoAAAANSUhEUgAAAFAAAAB9CAYAAAA1I+RFAAAABHNCSVQICAgI
....
Hc7GYuTuE23+EVbG/wE7dk77N6cYpQAAAABJRU5ErkJggg==
EEND

$icons['face_crying']=<<EEND
iVBORw0KGgoAAAANSUhEUgAAACAAAAAgCAYAAABzenr0AAAABHNCSVQICAgI
fAhkiAAAAAlwSFlzAAAN1wAADdcBQiibeAAAABl0RVh0U29mdHdhcmUAd3d3
...
31Ubdjyxtik75Th+55rrWLbzbO1ULTcJrJnruL1TMiGArs18rf0vPLcG1l08
LtAAAAAASUVORK5CYII=
EEND

$icons['face_smile_big']=<<EEND
iVBORw0KGgoAAAANSUhEUgAAACAAAAAgCAYAAABzenr0AAAABHNCSVQICAgI
.....
IQlXZwKuzrjtNLc0aDs1ABcd0k6ypVidf+6Owx6Eu22ZAAAAAElFTkSuQmCC
EEND

def get_icon_filename(name)
  raise("icon '#{name}' unknown in #{$icons.keys}") unless $icons[name]
  fname=File.join(Dir.tmpdir,name+".png")
  puts "#{name} ==> #{fname} / #{$icons[name].size}" if $DEBUG
  File.open(fname,"wb") { |f| f.write($icons[name].unpack('m')) } unless File.exists?(fname)
  fname
end
</code>

Here a little Shoes app for use raster content
<code>
require 'green_shoes'

<< "contents of 'icons64.rb' here" >>

Shoes.app do
  stack {
	background "#A0A0B0".."#A0A0FF"
	$icons.keys.each { |name|
			para name
			image get_icon_filename(name)
	}
  }
end

</code>

Or a Ruiby app (see https://github.com/raubarede/Ruiby):

<code>
require_relative 'Ruiby/lib/ruiby.rb'
<< "contents of 'icons64.rb' here" >>

class X < Ruiby_gtk
	def component()
	  stack do
		$icons.keys.each do |n| 
			flow { 
                           slot(label(n))
                           slot(label("#"+get_icon_filename(n) )) 
			}
		end
	  end
	end
end
Ruiby.start { X.new("test",100,100) }
</code>

                
  • zip
  • folder
  • Ruby
                    <code>
require 'zip/zip'
require 'zip/zipfilesystem'
include Zip

def compress(ppath)
	ppath.sub!(%r[/$],'')
	archive = File.join('./',File.basename(ppath))+'.zip'
	FileUtils.rm archive, :force=>true
	Zip::ZipFile.open(archive, 'w') do |zipfile|
		Dir["#{ppath}/**/**"].reject{|f|f==archive}.each do |file|
			zipfile.add(file.sub(ppath+'/',''),file)
		end
	end
end

# usage
temp = "./some_folder"
begin 
	compress(temp)                  # pack folder
	FileUtils.remove_dir(temp,true) # remove non empty folder, which is packed
end

</code>                
  • fork
  • detach
  • process
  • daemon
  • Ruby
                    Neat separation of responsibilities between fork/process stuff and actual app 

<code>
  #!/usr/bin/ruby

  daemonize do
    worker = Resque::Worker.new(*queues)
    worker.work
  end

  def daemonize █
    child = fork
    if child.nil? # is child
      $stdout.close
      $stdout = open("/dev/null")
      $stdin.close
      trap('HUP', 'IGNORE')
      block.call
    else # is parent
      Process.detach child
    end
  end
</code>