you are here: codestackercodes [RSS]leozera [RSS]

CSS Horizontal And Vertical Align JQuery Plugin

from: http://www.nealgrosskopf.com/tech/thread.asp?pid=37

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
<html>
<head>
<title>Demo</title>

<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">

<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.1/jquery.min.js"></script>

<script type="text/javascript">
(function ($) {
$.fn.vAlign = function() {
	return this.each(function(i){
	var h = $(this).height();
	var oh = $(this).outerHeight();
	var mt = (h + (oh - h)) / 2;	
	$(this).css("margin-top", "-" + mt + "px");	
	$(this).css("top", "50%");
	$(this).css("position", "absolute");	
	});	
};
})(jQuery);

(function ($) {
$.fn.hAlign = function() {
	return this.each(function(i){
	var w = $(this).width();
	var ow = $(this).outerWidth();	
	var ml = (w + (ow - w)) / 2;	
	$(this).css("margin-left", "-" + ml + "px");
	$(this).css("left", "50%");
	$(this).css("position", "absolute");
	});
};
})(jQuery);

$(document).ready(function() {
	$("#content").vAlign();
	$("#content").hAlign();
});
</script>

<style type="text/css">
html { background: #fafafa; }

#content
{
background: #fff;
border: 10px solid #eee;
padding: 20px;
color: #666;
font-family: Arial, Helvetica, sans-serif;
font-size: 12px;
line-height: 25px;
text-align: justify;
}

#content { width: 400px; }
</style>

</head>

<body>

<div id="content">
Lorem ipsum dolor sit amet, consectetur adipiscing elit. Maecenas eu dui eget nulla condimentum gravida. Vivamus erat leo, ultricies quis, gravida a, fringilla eu, urna. Pellentesque a mauris ac nisl semper egestas. Pellentesque ut elit in pede mattis gravida. Donec ac lectus a nisi suscipit placerat. Maecenas quis ipsum. Pellentesque mattis tellus. Suspendisse sollicitudin accumsan tortor. Pellentesque habitant morbi tristique senectus et netus et malesuada fames ac turpis egestas. Sed metus. Quisque et leo at erat rutrum lobortis. In tempus lectus eget ligula convallis tristique. 
</div>

</body>
</html>

rails pt-BR

traduzidos:
unidades de tempo, números, mensagens do active record, modelos (exemplo) e atributos (exemplo)

outros idiomas nesse repositório:
http://github.com/svenfuchs/rails-i18n/tree/e504448f1e0ef9e303c3f3f278c0b95622dfeb87/rails/locale

pt-BR: 

  date: 

    formats: 

      default: "%d/%m/%Y"

      short: "%d de %B"

      long: "%d de %B de %Y"

      only_day: "%d"

    

    day_names: [Domingo, Segunda, Terça, Quarta, Quinta, Sexta, Sábado]

    abbr_day_names: [Dom, Seg, Ter, Qua, Qui, Sex, Sáb]

    month_names: [~, Janeiro, Fevereiro, Março, Abril, Maio, Junho, Julho, Agosto, Setembro, Outubro, Novembro, Dezembro]

    abbr_month_names: [~, Jan, Fev, Mar, Abr, Mai, Jun, Jul, Ago, Set, Out, Nov, Dez]

    order: [:day,:month,:year]

  

  time: 

    formats: 

      default: "%A, %d de %B de %Y, %H:%M hs"

      time: "%H:%M hs"

      short: "%d/%m, %H:%M hs"

      long: "%A, %d de %B de %Y, %H:%M hs"

      only_second: "%S"

      datetime: 

        formats: 

          default: "%Y-%m-%dT%H:%M:%S%Z"

    am: ''

    pm: ''

  

  datetime: 

    distance_in_words: 

      half_a_minute: 'meio minuto'

      less_than_x_seconds:  

        one: 'menos de 1 segundo'

        other: 'menos de count segundos'

      

      x_seconds:  

        one: '1 segundo'

        other: 'count segundos'

      

      less_than_x_minutes:  

        one: 'menos de um minuto'

        other: 'menos de count minutos'

      

      x_minutes:  

        one: '1 minuto'

        other: 'count minutos'

      

      about_x_hours:  

        one: 'aproximadamente 1 hora'

        other: 'aproximadamente count horas'

      

      x_days:  

        one: '1 dia'

        other: 'count dias'

      

      about_x_months:  

        one: 'aproximadamente 1 mês'

        other: 'aproximadamente count meses'

      

      x_months:  

        one: '1 mês'

        other: 'count meses'

      

      about_x_years:  

        one: 'aproximadamente 1 ano'

        other: 'aproximadamente count anos'

      

      over_x_years:  

        one: 'mais de 1 ano'

        other: 'mais de count anos'

  

  number: 

    format: 

      precision: 3

      separator: ','

      delimiter: '.'

    currency: 

      format: 

        unit: 'R$'

        precision: 2

        format: '%u %n'

        separator: ','

        delimiter: '.'

    percentage: 

      format: 

        delimiter: '.'

    precision: 

      format: 

        delimiter: '.'

    human: 

      format: 

        precision: 1

        delimiter: '.'

  support: 

    array: 

      sentence_connector: "e"

      skip_last_comma: true              

    
  activerecord: 

      errors:

        template:

          header:

              one: "1 erro impediu que {{model}} fosse criado"

              other: "{{count}} erros impediram que {{model}} fosse criado"

          body: "Há algo errado a seguir"

        messages:

          inclusion: "não está incluiso na lista"

          exclusion: "é reservado"

          invalid: "é inválido"

          confirmation: "não confirma"

          accepted: "deve ser aceito"

          empty: "não pode estar vazio"

          blank: "não pode estar em branco"

          too_long: "é muito grande (máximo de {{count}} caracteres)"

          too_short: "é muito pequeno (mínimo de {{count}} caracteres)"

          wrong_length: "está no tamanho errado (deveria ter {{count}} caracteres)"

          taken: "já está sendo usado"

          not_a_number: "não é um número"

          greater_than: "deve ser maior que {{count}}"

          greater_than_or_equal_to: "deve ser maior que ou igual a {{count}}"

          equal_to: "deve ser igual a {{count}}"

          less_than: "deve ser menor que {{count}}"

          less_than_or_equal_to: "deve ser menor que ou igual a {{count}}"

          odd: "deve ser ímpar"

          even: "deve ser par"



      models:

          user: "usuário"

          

      attributes:

           user:

             login: "Usuário"

             email: "E-mail"

             password: "Senha"

             password_confirmation: "Confirmação da senha"

to_param

http://apidock.com/rails/Object/to_paramhttp://apidock.com/rails/Object/to_param#47-Better-slug-generation-essentially-a-to-param-replacement-

# create the slugify method

  class String
    def slugify
      returning self.downcase.gsub(/'/, '').gsub(/[^a-z0-9]+/, '-') do |slug|
        slug.chop! if slug.last == '-'
      end
    end
  end


#####################

# in model

  def to_param
    "#{id} #{title}".slugify
  end

import sql files into migrations

it's a small how to import a file in migrations.

from: http://code-ronin.com/articles/rails-migrations-directly-import-sql

# first, create the method import_sql:


class ActiveRecord::ConnectionAdapters::MysqlAdapter
  def import_sql(file)
    conf = ActiveRecord::Base.configurations[RAILS_ENV]
    sql_file = File.join(RAILS_ROOT, 'db', file + '.sql')
    cmd_line = "mysql -h "+conf["host"]+" -D "+conf["database"]+ " --user="+conf["username"]+" --password="+conf["password"]+" < "+sql_file
    raise Exception, "Error executing " + cmd_line unless system(cmd_line)    
  end
end


# create a migration. ex:


./script/generate migration sql_external_test

# save your sql file with sql commands in db/. migration's sample:


class SqlExternalTest < ActiveRecord::Migration
  def self.up
    import_sql("test")
  end

  def self.down
  end
end

find large files

sudo find / -type f -size +200000k -exec ls -lh {} \; | awk '{ print $9 ": " $5 }'

full screen button

fullScreen_btn.onRelease = fullScreen_btn.onReleaseOutside = toggleFullScreen;
	fullScreen_btn.onRollOver = onRollOverHandler;
	fullScreen_btn.onRollOut = onRollOutHandler;

	function onRollOverHandler()
	{
	}

	function onRollOutHandler():Void
	{

	}

	function toggleFullScreen():Void
	{
		if( Stage["displayState"] == "normal"){
			goFullScreen();
		} else {
			exitFullScreen();
		}
	}
	function goFullScreen():Void
	{
		   Stage["displayState"] = "fullScreen";
	}

	function exitFullScreen():Void
	{
	   Stage["displayState"] = "normal";
	}

render view without layout in ajax requests

http://jamiedubs.com/always-render-rails-views-without-the-full-layout-when-using-ajax-degradable-javascript

paste in application controller and forgot 'render :layout => false if request.xhr?'

  def render(*args)
    args.first[:layout] = false if request.xhr? and args.first[:layout].nil?
  	super
  end

current_action and current_controller helpers

create this helper and uses linkunlesscurrent_controller

def current_action?(options)
  url_string = CGI.escapeHTML(url_for(options))
  params = ActionController::Routing::Routes.recognize_path(url_string, :method => :get)
  params[:controller] == @controller.controller_name && params[:action] == @controller.action_name
end

def current_controller?(options)
  url_string = CGI.escapeHTML(url_for(options))
  params = ActionController::Routing::Routes.recognize_path(url_string, :method => :get)
  params[:controller] == @controller.controller_name
end

jquery twitter plugin

from: http://www.tidbits.com.br/download/exemplos/jquery.twitter/jquery.twitter_original.zip

<script type="text/javascript" src="jquery-1.2.6.pack.js"></script>
<script type="text/javascript" src="jquery.twitter.js"></script>

<script type="text/javascript">
<!--//--><![CDATA[//><!--

	$(document).ready(function() {
		$("#twitter").getTwitter({
			userName: "leozera",
			numTweets: 5,
			loaderText: "Loading tweets...",
			slideIn: true,
			showHeading: true,
			headingText: "Latest Tweets",
			showProfileLink: true
		});
	});
//--><!]]>

</script>

<div id="twitter"></div>

feedburner on rails

class PostsController < ApplicationController
  def show
    respond_to do |format|
      format.html
      format.rss do
        unless request.env['HTTP_USER_AGENT'].match(/feedburner|feedvalidator/i)
          redirect_to 'http://feeds.feedburner.com/myfeedburner', :status=>307
        end
      end
    end
  end
end

[edge rails] unified rendering

http://weblog.rubyonrails.org/2008/12/26/this-week-in-edge-rails

# currently:


render :file => '/tmp/random_file.erb'
render :template => 'other_controller/action'
render :action => 'show'

# rails 2.3


render '/tmp/random_file.erb'
render 'other_controller/action'
render 'show'
render :show

paperclip running in passenger

it's necessary set the correct path of imagemagick. in os x (dev) e linux (production):

if RAILS_ENV == "development" 
  Paperclip.options[:image_magick_path] = '/opt/local/bin/' 
else 
  Paperclip.options[:image_magick_path] = '/usr/bin/' 
end 

rmagick install on leopard

sudo port install tiff -macosx
sudo port install jpeg
sudo port install libpng
sudo port install libwmf
sudo port install lcms
sudo port install freetype
sudo port install ghostscript
sudo port install GraphicsMagick
sudo port install ImageMagick
sudo gem install rmagick

list ruby files

The $LOADED_FEATURES variable contains a list of all the files that have been required by your program.

p $LOADED_FEATURES

custom layout

class ApplicationController < ActionController::Base    

  layout :custom_layout

  private
    def custom_layout
      logged_in? ? 'member' : 'guest'
    end

end

textmate's shortcuts

ctrl+shift+> = open and close erb tags <% = %>
alt+command+] = auto indent highlighted code
ctrl+shift+w = auto put html tags around highlighted code
alt+command+> = auto close tag
ctrl+command+w = close all open tabs
alt+command+a = type on the end of multiple lines of highlighted code

read/write text files with ruby

source: http://rubylearning.com/satishtalim/read_write_files.html

# Open and read from a text file  

# Note that since a block is given, file will  

# automatically be closed when the block terminates  

File.open('p014constructs.rb', 'r') do |f1|  
  while line = f1.gets  
    puts line  
  end  
end  
  
# Create a new file and write to it  

File.open('test.rb', 'w') do |f2|  
  # use "\n" for two lines of text  

  f2.puts "Created by Satish\nThank God!"  
end  

tail a file with ruby

def tail(filename, lines=10)
  buffer = []
  print_buffer = ''

  File.open(filename, 'r') do |f1|  
    while line = f1.gets  
      buffer << line
    end  
  end

  unless buffer.empty?
    p1 = 0
    p2 = buffer.length
    p1 = p2 - 10 if p2 > 10
    print_buffer = buffer[p1..p2].join 
  end

  print_buffer
end

puts tail('file.txt')

trim a string in words

def trim_by_words(string,wordcount) 
  string.split[0..(wordcount-1)].join(" ") +(string.split.size > wordcount ? "..." : "") 
end

# example

string = "Lorem Ipsum is simply dummy text of the printing and typesetting industry."

puts trim_by_words(string,10) # returns: Lorem Ipsum is simply dummy text of the printing and...

[rails] create_table methods

  create_table :table do |t|
    t.column # adds an ordinary column. Ex: t.column(:name, :string)

    t.index # adds a new index.

    t.timestamps
    t.change # changes the column definition. Ex: t.change(:name, :string, :limit => 80)

    t.change_default # changes the column default value.

    t.rename # changes the name of the column.

    t.references
    t.belongs_to
    t.string
    t.text
    t.integer
    t.float
    t.decimal
    t.datetime
    t.timestamp
    t.time
    t.date
    t.binary
    t.boolean
    t.remove
    t.remove_references
    t.remove_belongs_to
    t.remove_index
    t.remove_timestamps
  end
Displaying Code 161 - 180 of 270 in total