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

find php.ini path

php -i | grep php.ini

basic jquery events

$('.box_1').bind('click', function(){
  alert("Clicked Box 1");
});

$('.box_2').click(function(){
  alert("Clicked Box 2");
});

$('.box_3').click(function(){
  $(this).css('background', '#8C0')
});

$('.box_4').bind('dblclick', function(){
  $(this).text('Double Clicked');
});

$('.box_5').mouseenter(function(){
  $(this).css('background', '#C60');
}).mouseleave(function(){
  $(this).css('background', '#06C')
})

$('.box_6').hover(function(){
  // In

  $(this).text('IN')
}, function(){
  // Out

  $(this).text('OUT')
})

google-like css 3 button

http://www.zurb.com/playground/google-buttons

button.g-button, a.g-button, input[type=submit].g-button {
padding: 6px 10px;
-webkit-border-radius: 2px 2px;
border: solid 1px rgb(153, 153, 153);
background: -webkit-gradient(linear, 0% 0%, 0% 100%, from(rgb(255, 255, 255)), to(rgb(221, 221, 221)));
color: #333;
text-decoration: none;
cursor: pointer;
display: inline-block;
text-align: center;
text-shadow: 0px 1px 1px rgba(255,255,255,1);
line-height: 1;
}

iphone: prevent copy paste

* {
   -webkit-user-select: none;  /* prevent copy paste for all elements */
} 

humanize secs

source: http://stackoverflow.com/questions/4136248/how-to-generate-a-human-readable-time-range-using-ruby-on-rails

def humanize secs
  [[60, :seconds], [60, :minutes], [24, :hours], [1000, :days]].map{ |count, name|
    if secs > 0
      secs, n = secs.divmod(count)
      "#{n.to_i} #{name}"
    end
  }.compact.reverse.join(' ')
end

p humanize 1234
#=>"20 minutes 34 seconds"

p humanize 12345
#=>"3 hours 25 minutes 45 seconds"

p humanize 123456
#=>"1 days 10 hours 17 minutes 36 seconds"

p humanize(Time.now - Time.local(2010,11,5))
#=>"4 days 18 hours 24 minutes 7 seconds"

.htaccess examples

RewriteEngine On 
RewriteCond %{REQUEST_FILENAME} !-f 
RewriteCond %{REQUEST_FILENAME} !-d 
RewriteRule ^(.*)$ $1.php [L,QSA] 
# http://domain/about -> http://domain/about.php 

RewriteRule ^(.*)$ index.php?q=$1 [L,QSA] 
# http://domain/about -> http://domain/index.php?q=about 

sending email with pony

Pony.mail(:to => 'email@provider.com', :via => :smtp, :via_options => {
:address => 'smtp.gmail.com',
:port => '587',
:enable_starttls_auto => true,
:user_name => 'id_gmail',
:password => 'parola_gmail',
:authentication => :plain, # :plain, :login, :cram_md5, no auth by default

:domain => "HELO", # don't know exactly what should be here

},
:subject => 'hi', :body => 'Hello there.')

fetching tweets with jquery

$(document).ready(function() {
    // Declare variables to hold twitter API url and user name

    var twitter_api_url = 'http://search.twitter.com/search.json';
    var twitter_user    = 'leozera';

    // Enable caching

    $.ajaxSetup({ cache: true });

    // Send JSON request

    // The returned JSON object will have a property called "results" where we find

    // a list of the tweets matching our request query

    $.getJSON(
        twitter_api_url + '?callback=?&rpp=5&q=from:' + twitter_user,
        function(data) {
            $.each(data.results, function(i, tweet) {
                // Uncomment line below to show tweet data in Fire Bug console

                // Very helpful to find out what is available in the tweet objects

                //console.log(tweet);


                // Before we continue we check that we got data

                if(tweet.text !== undefined) {
                    // Calculate how many hours ago was the tweet posted

                    var date_tweet = new Date(tweet.created_at);
                    var date_now   = new Date();
                    var date_diff  = date_now - date_tweet;
                    var hours      = Math.round(date_diff/(1000*60*60));

                    // Build the html string for the current tweet

                    var tweet_html = '<div class="tweet_text">';
                    tweet_html    += '<a href="http://www.twitter.com/';
                    tweet_html    += twitter_user + '/status/' + tweet.id + '">';
                    tweet_html    += tweet.text + '<\/a><\/div>';
                    tweet_html    += '<div class="tweet_hours">' + hours;
                    tweet_html    += ' hours ago<\/div>';

                    // Append html string to tweet_container div

                    $('#tweet_container').append(tweet_html);
                }
            });
        }
    );
});

Array method to return array elements as quoted strings

class Array
  def to_quoted_s(q="'")
    "#{q}#{self.join("#{q}, #{q}")}#{q}"
  end
end

# Example:


a = ['a', 'b', 'c', 'd', 'e']
puts a.to_s # abcde

puts a.to_quoted_s # 'a', 'b', 'c', 'd', 'e'

puts a.to_quoted_s("\"") # "a", "b", "c", "d", "e"

flash_messages helper method to rails 3

def flash_messages 
  %w(notice warning error).each do |msg| 
    concat content_tag(:div, content_tag(:p, flash[msg.to_sym]), :class => msg) unless flash[msg.to_sym].blank? 
  end 
end

finding large files

find . -size +20000k -exec du -h {} \;

listing files in a directory with rails

via Shairon Toledo @ rails-br

Dir.glob("*").each{|f|  puts "Name: #{f} | Created at: #{File.ctime(f)} | Updated at: #{File.mtime(f)}"   }

smooth scrolling with jquery

// Smooth scrolling within page anchors

$('a[href*=#]').click(function() {
    
  if (location.pathname.replace(/^\//,'') == this.pathname.replace(/^\//,'') && location.hostname == this.hostname) {
        
        var $target = $(this.hash);
            
        $target = $target.length && $target || $('[name=' + this.hash.slice(1) +']');
            
        if ($target.length) {
              var targetOffset = $target.offset().top;
              $('html,body').animate({scrollTop: targetOffset}, 1000);
              return false;       
        }      
     }        
});

post in twitter using rest_client

http://github.com/adamwiggins/rest-client

require "rubygems"
require "rest_client"

RestClient::Resource.new("http://twitter.com/statuses/update.json", :user => "user", :password => "pass").post :status => "Hello, there!"

rails 3 two lines install

gem install i18n tzinfo builder memcache-client rack rack-test rack-mount erubis mail text-format thor bundler

gem install rails --pre

clean way to open a popup window

$('a.popup').live('click', function(){
	newwindow=window.open($(this).attr('href'),'','height=200,width=150');
	if (window.focus) {newwindow.focus()}
	return false;
});

seletores do jquery

http://docs.jQuery.com/DOM/Traversing/Selectors

$('h1') // elementos h1

$('#meuID') // elementos com id "meuID"

$('.minhaClasse') // elementos definidos com a classe "minhaClasse"

$('[width]') // elementos que possuem o atributo width definido

$('[width=500]') // elementos que possuem o atributo width definido como 500

$('img[width=300]') // imagens que possuem largura = 300

$('img[src$=png]') // imagens com final png

$('a[href^=http://localhost]') // links que comecem com http://localhost

$('a[href$=pdf]') // links com final pdf

$('a[href*=www]') // links que contém www

$(':empty') // elementos vazio

$('div:empty') // elementos div vazios

$(':has(p)') // todos elementos que tenham um parágrafo

$('div:has(a)'); // elementos div que possuem link

$("p:contains('dinei')") // parágrafos que contém a palavra "dinei"

$("p:eq(0)") // seleciona o primeiro elemento p

i18n in labels

rails 2.3.4 doen't have i18n support in labels

http://lawrencesong.net/2009/04/i18n-label-in-rails-monkey-patch/

module ActionView 
  module Helpers 
    class InstanceTag 
      def to_label_tag_with_i18n(text = nil, options = {}) 
        text ||= object.class.human_attribute_name(method_name) if object.class.respond_to?(:human_attribute_name) 
 
        to_label_tag_without_i18n(text, options) 
      end 
 
      alias_method_chain :to_label_tag, :i18n 
    end 
  end 
end

paperclip refresh all images

run this task

rake paperclip:refresh class=MyClass

use default_scope to set up default find conditions such as order

class MyModel < ActiveRecord::Base
  default_scope :order => 'created_at desc'
end
Displaying Code 101 - 120 of 270 in total