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

About this user

Fjölnir �sgeirsson http://ninjakitten.us

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

Matrix rotator

This method rotates a matrix
Example output:
~/Desktop% ruby rotate.rb
normal
12345
00000
fooba
rotated left
50a
40b
30o
20o
10f
rotated right
f01
o02
o03
b04
a05

def rotateMatrix(matrix, direction)
  # - You must Rotate the matrix neo!
  oldMap = matrix

  # Get the number of lines in the old map (they're the new columns)
  lineCount = oldMap.size
  # Get the number of columns in the old map (We have that many rows now)
  columnCount = oldMap[0].size
  @map = []
  columnCount.times { @map.push [] }

  # Loop through every line in the old map, retrieve the appropriate column
  # and make a horizontal column with it's contents
  # we'll take one (old)line at a time and rotate it.
  onLine = 0
  oldMap.each do |oldLine|
    onColumn = 0
    oldLine.each do
      case direction
      when :right
        @map[(columnCount - 1) - onColumn][(lineCount - 1) - onLine] = oldLine[(columnCount - 1) - onColumn]
      when :left
        @map[onColumn][onLine] = oldLine[(columnCount - 1) - onColumn]
      end
      onColumn += 1
    end
    onLine += 1
  end
  @map
end

def rotateRight(matrix)
  rotateMatrix(matrix, :right)
end

def rotateLeft(matrix)
  rotateMatrix(matrix, :left)
end

File icon giver/getter/whatever

This code uses acts_as_attachment (that's the attachment.filename) but you can of course replace it with anything.
It gets the file extension then looks up that extension in a dir full of files named extension.png
if none is found, unknown.png is used


<%
extension = File.extname(attachment.filename).gsub(/\./, "")
# get a file icon
icon_path = nil
Dir.entries("#{RAILS_ROOT}/public/images/filetypes").each do |entry|
	entry_extension = File.extname(entry)
	if entry.gsub(entry_extension, "") === extension
		icon_path = "/images/filetypes/" + entry
		break
	end
end
icon_path = "/images/filetypes/unknown.png" if icon_path.nil?
 %>
<%= image_tag icon_path %>
<span class="attachment_name"><%= attachment.filename %></span><br />

all_children!

This snippet just gives you all the children of a model that acts_as_tree

  def all_children
    Page.all_children_for self
  end
  
  def self.all_children_for(parent, arr = [])
    parent.children.each { |child| arr.push child }
    parent.children.each { |child| all_children_for child, arr }
    arr
  end
« Newer Snippets
Older Snippets »
Showing 1-3 of 3 total  RSS