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

Voloshin Ruslan http://rubyclub.com.ua/

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

create new rails rake task

Create new task for /unit/helpers/*_test.rb

Rakefile
namespace :test do
  Rake::TestTask.new(:helpers) do |t|
    t.libs << "test"
    t.pattern = 'test/unit/helper/*_test.rb'
    t.verbose = true
  end

  Rake::Task['test:helpers'].invoke
end

Save db data to fixture files

rake db:fixtures:dump_all
он сохранит все данные из ваших таблиц development базы в ямлы для тестов rake

db:fixtures:dump_references
["areas","countries"]
сохранит только те таблицы которы епрописаны у него в конфиге, в данном случае это

namespace :db do
  namespace :fixtures do

    desc 'Create YAML test fixtures from data in an existing database.
Defaults to development database. Set RAILS_ENV to override.'
    task :dump_all => :environment do
      sql = "SELECT * FROM %s"
      skip_tables = ["schema_info"]
      ActiveRecord::Base.establish_connection(:development)
      (ActiveRecord::Base.connection.tables - skip_tables).each do |table_name|
        i = "000"
        File.open("#{RAILS_ROOT}/test/fixtures/#{table_name}.yml", 'w') do |file|
          data = ActiveRecord::Base.connection.select_all(sql % table_name)
          file.write data.inject({}) { |hash, record|
            hash["#{table_name}_#{i.succ!}"] = record
            hash
          }.to_yaml
        end
      end
    end
  end
  
  namespace :fixtures do
    desc 'Create YAML test fixtures for references. Defaults to development database. 
    Set RAILS_ENV to override.'
    task :dump_references => :environment do
      sql = "SELECT * FROM %s"
      dump_tables = ["areas","countries"]
      ActiveRecord::Base.establish_connection(:development)
      dump_tables.each do |table_name|
        i = "000"
        file_name = "#{RAILS_ROOT}/test/fixtures/#{table_name}.yml"
        p "Fixture save for table #{table_name} to #{file_name}"
        File.open(file_name, 'w') do |file|
          data = ActiveRecord::Base.connection.select_all(sql % table_name)
          file.write data.inject({}) { |hash, record|
            hash["#{table_name}_#{i.succ!}"] = record
            hash
          }.to_yaml
        end
      end
    end
  end
end 

Customize error_messages_for

// description of your code here

 module ActionView::Helpers::ActiveRecordHelper
   def error_messages_for(object_name, options = {})
    options = options.symbolize_keys
    object = instance_variable_get("@#{object_name}")
    if object && !object.errors.empty?
      content_tag("div",
      content_tag(
      options[:header_tag] || "h2",
      "Возникло #{object.errors.count} ошибок при сохранении"
      ) +
      content_tag("p", "Проблеммы возникли для следующих полей:") +
      content_tag("dl", object.errors.full_messages.collect { |msg| content_tag("dt", msg) }),
      "id" => options[:id] || "errorExplanation", "class" => options[:class] || "errorExplanation"
      )
    else
      ""
    end
  end
 end
  

clear directory with svn files

// description of your code here
It command line clear svn directory
find d . -name .svn -exec rm -rf '{}' \; -print

Check email in html form

// description of your code here

 <script type="text/javascript">
        function check_email(email_id,err_id){
            emailRegExp = /^[_a-z0-9-]+(\.[_a-z0-9-]+)*@[a-z0-9-]+(\.[a-z0-9-]+)*(\.([a-z]){2,4})$/;
            var err_mail='Email addres incorect!';
            if(emailRegExp.test(document.getElementById(email_id).value)){
                alert('true');
                return true;
            }else{
                document.getElementById(err_id).innerHTML=err_mail;
                alert(err_mail);
                return false;
            }
        }
    </script>

        <span id="err_msg" style="color: red;"></span>
    <form id="myForm" name="myForm" action="./register.php" method="post" onsubmit="return check_email('email','err_msg');">
        <input type="text" name="email" id="email"/>
        <input  type="submit" name="send" value="Send" />
    </form>

Convert mail to image (guard mail) from spam

// description of your code here

<?php

if(empty($_GET['sid'])){
	//write html for image
	$mail='example@domain.com';
    $text=base64_encode(serialize($mail));
	echo '<img src="imgmail.php?sid='.$text.'" /><br/>';
}else{
	//show coded mail image
	$text=$_GET['sid'];
	header("Content-type: image/gif");	
	echo mail_to_image($text);
}

function mail_to_image($ctext='no mail'){
	$text=unserialize(base64_decode($ctext));
    $size=strlen($text)*8;
    $im = @imagecreate($size, 20) or die("Cannot Initialize new GD image stream");
    $background_color = imagecolorallocate($im, 255, 255, 255);
    $text_color = imagecolorallocate($im, 0, 0, 0);
    imagestring($im,3, 5, 5,  $text , $text_color);
    return imagegif($im);
}
?> 

Pinging site

Вот простой пример как пропинговывать сайты при новых постах без включения допоплнительных плагинов и модулей

irb(main):032:0>
irb(main):033:0* server = XMLRPC::Client.new("blogsearch.google.com", "/ping/RPC2", 80)
=> #<XMLRPC::Client:0x2aaaaeb222e8 @create=nil, @port=80, @http=#<Net::HTTP blogsearch.google.com:80 open=false>, @proxy_host=nil, @http_last_response=nil, @parser=nil, @timeout=30, @path="/ping/RPC2", @password=nil, @http_header_extra=nil, @use_ssl=false, @host="blogsearch.google.com", @user=nil, @proxy_port=nil, @auth=nil, @cookie=nil>
irb(main):034:0> server.call("weblogUpdates.extendedPing", 'Rubyclub.com.ua new on site','http://rubyclub.com.ua/', 'http://rubyclub.com.ua/messages/rss')
=> {"message"=>"Thanks for the ping.", "flerror"=>false}

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