<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0" xmlns:dc="http://purl.org/dc/elements/1.1/">
  <channel>
    <title>DZone Snippets: Mickael's Code Snippets</title>
    <link>http://snippets.dzone.com/posts</link>
    <pubDate>Sun, 27 Jul 2008 03:32:37 GMT</pubDate>
    <description>DZone Snippets: Mickael's Code Snippets</description>
    <item>
      <title>Add rails log to console</title>
      <link>http://snippets.dzone.com/posts/show/4371</link>
      <description>In order to show rails log in console, add theses lines to your .irbrc&lt;br /&gt;&lt;br /&gt;&lt;code&gt;&lt;br /&gt;if ENV.include?('RAILS_ENV')&amp;&amp; !Object.const_defined?('RAILS_DEFAULT_LOGGER')&lt;br /&gt;  Object.const_set('RAILS_DEFAULT_LOGGER', Logger.new(SDTOUT))&lt;br /&gt;end&lt;br /&gt;&lt;/code&gt;</description>
      <pubDate>Tue, 31 Jul 2007 11:16:56 GMT</pubDate>
      <guid>http://snippets.dzone.com/posts/show/4371</guid>
      <author>Mickael (Mickael)</author>
    </item>
    <item>
      <title>Converting Mysql Tables in InnoDB</title>
      <link>http://snippets.dzone.com/posts/show/4327</link>
      <description>// description of your code here&lt;br /&gt;&lt;br /&gt;&lt;code&gt;&lt;br /&gt;class ConvertMysqlToInnodb &lt; ActiveRecord::Migration&lt;br /&gt; def self.up&lt;br /&gt;   config = ActiveRecord::Base.configurations&lt;br /&gt;   begin&lt;br /&gt;     STDERR.puts "Migrating all existing tables to InnoDB"&lt;br /&gt;     schema = []&lt;br /&gt;     select_all('SHOW TABLES').inject([]) do |schema, table|&lt;br /&gt;       schema &lt;&lt; "ALTER TABLE #{table.to_a.first.last} ENGINE=InnoDB"&lt;br /&gt;     end&lt;br /&gt;     schema.each { |line| execute line }&lt;br /&gt;   end if config[RAILS_ENV]['adapter'] == 'mysql' unless $schema_generator&lt;br /&gt; end&lt;br /&gt;source http://trac.typosphere.org/browser/trunk/db/migrate/015_convert_mysql_to_innodb.rb&lt;br /&gt;&lt;br /&gt; def self.down&lt;br /&gt;   # don't do anything&lt;br /&gt;   # this is a one-way migration, but it's not "irreversable"&lt;br /&gt;   # because it doesn't change any code logic&lt;br /&gt; end&lt;br /&gt;end&lt;br /&gt;&lt;/code&gt;</description>
      <pubDate>Thu, 19 Jul 2007 12:43:43 GMT</pubDate>
      <guid>http://snippets.dzone.com/posts/show/4327</guid>
      <author>Mickael (Mickael)</author>
    </item>
    <item>
      <title>Daemonize a Ruby process</title>
      <link>http://snippets.dzone.com/posts/show/3646</link>
      <description>// description of your code here&lt;br /&gt;from : http://scie.nti.st/2006/12/15/daemonize-a-ruby-process&lt;br /&gt;Here's a neat thing I found. I needed a small bit of Ruby code to run continuously in the background, but because of how Capistrano can't seem to work well with "nohup" and "&amp;" (background job), my ruby script itself needed to be able to fork and detach from the terminal. Here's how you do it: &lt;br /&gt;&lt;code&gt;&lt;br /&gt;#!/usr/bin/ruby&lt;br /&gt;&lt;br /&gt;pid = fork do&lt;br /&gt;  Signal.trap('HUP', 'IGNORE') # Don't die upon logout&lt;br /&gt;&lt;br /&gt;  loop do&lt;br /&gt;&lt;br /&gt;    // Some code&lt;br /&gt;&lt;br /&gt;    sleep 60&lt;br /&gt;  end&lt;br /&gt;end&lt;br /&gt;&lt;br /&gt;Process.detach(pid)&lt;br /&gt;&lt;/code&gt;</description>
      <pubDate>Thu, 08 Mar 2007 09:42:01 GMT</pubDate>
      <guid>http://snippets.dzone.com/posts/show/3646</guid>
      <author>Mickael (Mickael)</author>
    </item>
    <item>
      <title>Generate random password in ruby </title>
      <link>http://snippets.dzone.com/posts/show/3632</link>
      <description>Aaron Blohowiak suggests adding this as a public method in user.rb:&lt;br /&gt;  &lt;br /&gt;&lt;br /&gt;&lt;code&gt;&lt;br /&gt;def new_random_password&lt;br /&gt;  self.password= Digest::SHA1.hexdigest("--#{Time.now.to_s}--#{login}--")[0,6]&lt;br /&gt;  self.password_confirmation = self.password&lt;br /&gt;end&lt;br /&gt;&lt;/code&gt;</description>
      <pubDate>Tue, 06 Mar 2007 08:51:55 GMT</pubDate>
      <guid>http://snippets.dzone.com/posts/show/3632</guid>
      <author>Mickael (Mickael)</author>
    </item>
    <item>
      <title>Init rails project script</title>
      <link>http://snippets.dzone.com/posts/show/3483</link>
      <description>From http://vinsol.com/2007/02/08/ruby-script-for-creating-new-rails-project-and-initial-svn-import-with-ignoringremoving-logother-files&lt;br /&gt;&lt;br /&gt;&lt;code&gt;&lt;br /&gt;require 'fileutils'&lt;br /&gt;&lt;br /&gt;puts  "########################################"&lt;br /&gt;puts  "This script creates a new rails project and do the initial svn import with ignoring/deleting files from subversion"&lt;br /&gt;puts  "Please send your feedback to Akhil Bansal&lt;bansalakhil30.10@gmail.com&gt;"&lt;br /&gt;puts  "I have tested this script and it works great on my system."&lt;br /&gt;puts  ""&lt;br /&gt;puts  ""&lt;br /&gt;puts  "                    ###### ATTENTION #######"&lt;br /&gt;puts  ""&lt;br /&gt;puts  ""&lt;br /&gt;puts  "Use this script at your own risk, if your computer explodes its not my fault :-) "&lt;br /&gt;puts  "#######################################"&lt;br /&gt;&lt;br /&gt;puts  "Enter svn username: "&lt;br /&gt;username = gets.strip&lt;br /&gt;puts  "Enter the svn url: "&lt;br /&gt;svn_url =gets.strip&lt;br /&gt;&lt;br /&gt;puts  "Enter Rails Application Path:(eg: /home/akhil/ror): "&lt;br /&gt;app_path = gets.strip&lt;br /&gt;puts  "Enter Application Name: "&lt;br /&gt;app_name = gets.strip&lt;br /&gt;&lt;br /&gt;puts  "######################################"&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;puts  "Please verify the following variables: "&lt;br /&gt;puts  "Svn Username: #{username}"&lt;br /&gt;puts  "Svn URL: #{svn_url}"&lt;br /&gt;puts  "Application Path: #{app_path}"&lt;br /&gt;puts  "Application name: #{app_name}"&lt;br /&gt;&lt;br /&gt;puts  "Proceed (y/n)"&lt;br /&gt;proceed = gets&lt;br /&gt;proceed = proceed.strip.upcase&lt;br /&gt;if proceed == 'N' &lt;br /&gt;    puts  "Terminating..."&lt;br /&gt;    exit 0&lt;br /&gt;elsif proceed == 'Y' &lt;br /&gt;    if system("rails -v")&lt;br /&gt;      s="/"&lt;br /&gt;    elsif   system("rails.cmd -v")&lt;br /&gt;      s="\\"&lt;br /&gt;    else&lt;br /&gt;        puts "Cannot find rails. Terminating..."&lt;br /&gt;        exit 0&lt;br /&gt;    end    &lt;br /&gt;    app_root=app_path+s+ app_name&lt;br /&gt;    &lt;br /&gt;    puts  "Generating rails project: (#{app_root})"&lt;br /&gt;    if system("rails #{app_root}")&lt;br /&gt;      s="/"&lt;br /&gt;    elsif   system("rails.cmd #{app_root}")&lt;br /&gt;      s="\\"&lt;br /&gt;    else&lt;br /&gt;        puts "Cannot create rails project. Terminating..."&lt;br /&gt;        exit 0&lt;br /&gt;    end    &lt;br /&gt;    &lt;br /&gt;    puts  "SVNinitial import: "&lt;br /&gt;    system("svn import #{app_root} #{svn_url} -m \"Initial Import\" --username #{username}")&lt;br /&gt;   &lt;br /&gt;    FileUtils.remove_dir(app_root, true)&lt;br /&gt;   &lt;br /&gt;    puts  "Checking out from svn: "&lt;br /&gt;&lt;br /&gt;    system("svn checkout #{svn_url} #{app_root}")&lt;br /&gt;    FileUtils.cd(app_root, :verbose =&gt; true)&lt;br /&gt;    &lt;br /&gt;    puts  "Removing all log files from SVN"&lt;br /&gt;    system("svn remove log"+s+"*")&lt;br /&gt;    puts  "commiting..."&lt;br /&gt;    system("svn commit -m \"removing all log files from subversion \" ")&lt;br /&gt;    puts  "Ignoring all log files under log dir"&lt;br /&gt;    system("svn propset svn:ignore \"*.log\" log"+s)&lt;br /&gt;    puts  "Updating and commiting..."&lt;br /&gt;    system("svn update log"+s)&lt;br /&gt;    system("svn commit -m \"Ignoring all files in "+s+"log"+s+" ending in .log \" ")&lt;br /&gt;    puts  "Removing tmp directory from SVN"&lt;br /&gt;    system("svn remove tmp"+s)&lt;br /&gt;    puts  "commiting..."&lt;br /&gt;    system("svn commit -m \"removing the temp directory from subversion \" ")&lt;br /&gt;    puts  "Ignoring tmp dir"&lt;br /&gt;    system("svn propset svn:ignore \"*\" tmp"+s)&lt;br /&gt;    puts  "Updating and commiting again...."&lt;br /&gt;&lt;br /&gt;    system("svn update tmp"+s)&lt;br /&gt;    system("svn commit -m \"Ignore the whole tmp"+s+" directory, might not work on subdirectories? \" ")&lt;br /&gt;    puts  "Moving database.yml to database.example"&lt;br /&gt;    system("svn move config"+s+"database.yml config"+s+"database.example")&lt;br /&gt;    puts  "commiting..."&lt;br /&gt;    system("svn commit -m \"Moving database.yml to database.example to provide a template for anyone who checks out the code \" ")&lt;br /&gt;    puts  "Ignoring database.yml , updating and commiting..."&lt;br /&gt;    system("svn propset svn:ignore 'database.yml' config"+s)&lt;br /&gt;    system("svn update config"+s)&lt;br /&gt;    system("svn commit -m \"Ignoring database.yml\" ")&lt;br /&gt;    puts  "Finished."&lt;br /&gt;&lt;br /&gt;else&lt;br /&gt;    puts  "Unknown Input. Terminating..."&lt;br /&gt;	exit 0&lt;br /&gt;end&lt;br /&gt;&lt;/code&gt;</description>
      <pubDate>Fri, 09 Feb 2007 12:52:42 GMT</pubDate>
      <guid>http://snippets.dzone.com/posts/show/3483</guid>
      <author>Mickael (Mickael)</author>
    </item>
    <item>
      <title>Property change listener</title>
      <link>http://snippets.dzone.com/posts/show/3480</link>
      <description>How to implement a Property change listener on ruby class&lt;br /&gt;Origin : http://rawblock.blogspot.com/2007/02/transparent-property-change-listeners.html &lt;br /&gt;&lt;br /&gt;&lt;code&gt;&lt;br /&gt;class ListenerSupport&lt;br /&gt; &lt;br /&gt;  def self.listen_to(klass, *properties)&lt;br /&gt;    setup(klass)&lt;br /&gt;    properties.each do |p|&lt;br /&gt;      klass.instance_eval do&lt;br /&gt;        #rename original method&lt;br /&gt;        alias_method "#{p}_orig=", "#{p}="&lt;br /&gt;        #create proxy method in it's place that will fire&lt;br /&gt;        #changes, and delegate to the original implementation&lt;br /&gt;        define_method "#{p}=" do |value|&lt;br /&gt;          old_value = send "#{p}"&lt;br /&gt;          send "#{p}_orig=",value&lt;br /&gt;          fire_property_changed p, old_value, value&lt;br /&gt;        end&lt;br /&gt;      end&lt;br /&gt;    end&lt;br /&gt;  end&lt;br /&gt; &lt;br /&gt;  def self.setup(klass)&lt;br /&gt;    klass.instance_eval do&lt;br /&gt;     &lt;br /&gt;      define_method :fire_property_changed do |prop, pre, post|&lt;br /&gt;        return if pre == post&lt;br /&gt;        eval %{&lt;br /&gt;          @listeners[prop].each do |l|&lt;br /&gt;              l.property_changed(self, prop, pre, post)&lt;br /&gt;          end unless @listeners.nil?&lt;br /&gt;        }&lt;br /&gt;      end unless instance_methods.include? :fire_property_changed&lt;br /&gt;     &lt;br /&gt;      define_method :add_property_listener do |prop, listener|&lt;br /&gt;        eval %{&lt;br /&gt;          @listeners = {} if @listeners.nil?&lt;br /&gt;          prop_listeners = @listeners.include?(prop) ? @listeners[prop] : []&lt;br /&gt;          @listeners[prop] = prop_listeners&lt;br /&gt;          prop_listeners &lt;&lt; listener unless prop_listeners.include? listener&lt;br /&gt;        }&lt;br /&gt;      end unless instance_methods.include? :add_property_listener&lt;br /&gt;     &lt;br /&gt;    end&lt;br /&gt;  end&lt;br /&gt; &lt;br /&gt;end&lt;br /&gt;&lt;/code&gt;&lt;br /&gt;&lt;br /&gt;The general idea is that the original class is modified so that all properties that are listened to have their accessor write methods intercepted, and any property change listeners are notified when that property changes.&lt;br /&gt;&lt;br /&gt;Let's walk through how it works:&lt;br /&gt;&lt;br /&gt;    * A standard Ruby class with property accessors is created. e.g.&lt;br /&gt;&lt;br /&gt;      class RubyBean&lt;br /&gt;        attr_accessor :foo, :bar&lt;br /&gt;      end&lt;br /&gt;&lt;br /&gt;    * A call to ListenerSupport.listen_to is made to modify the class to allow properties to be listened to.&lt;br /&gt;&lt;br /&gt;      ListenerSupport.listen_to RubyBean, :foo, :bar&lt;br /&gt;&lt;br /&gt;    * listen_to adds methods add_property_listener and fire_property_changed to allow listeners to be added to RubyBean for specific properties.&lt;br /&gt;    * listen_to then aliases the original methods foo= and bar= to foo_orig= and bar_orig=. New methods for foo= and bar= are defined that delegate the work to the original method, then call fire_property_changed to notify the listeners.&lt;br /&gt;    * Listeners are called, and any custom action (such as GUI component binding) can be carried out.&lt;br /&gt;</description>
      <pubDate>Thu, 08 Feb 2007 16:00:35 GMT</pubDate>
      <guid>http://snippets.dzone.com/posts/show/3480</guid>
      <author>Mickael (Mickael)</author>
    </item>
    <item>
      <title>Putting the errors in the right place</title>
      <link>http://snippets.dzone.com/posts/show/3403</link>
      <description>The idea is to display the error near the field instead of in global area at the top of the page.&lt;br /&gt;Simple&#8230; first go into your view and delete the&lt;br /&gt;&lt;code&gt;&lt;br /&gt;error_messages_for &#8216;object&#8217;&lt;br /&gt;&lt;/code&gt;&lt;br /&gt;&lt;br /&gt;Then stick this in your application helper.&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;# application_helper.rb&lt;br /&gt;def error_for(object, method = nil, options={})&lt;br /&gt;  if method&lt;br /&gt;    err = instance_variable_get("@#{object}").errors.on(method).to_sentence     rescue instance_variable_get("@#{object}").errors.on(method)&lt;br /&gt;  else&lt;br /&gt;     err = @errors["#{object}"] rescue nil&lt;br /&gt;  end&lt;br /&gt;  options.merge!(:class=&gt;&#8217;fieldWithErrors&#8217;,&lt;br /&gt;          :id=&gt;"#{[object,method].compact.join(&#8217;_')}-error",&lt;br /&gt;:style=&gt;(err ? #{options[:style]}":"#{options[:style]};display: none;")&lt;br /&gt;   )&lt;br /&gt; content_tag("p",err || "", options )     &lt;br /&gt;end&lt;br /&gt;&lt;/code&gt;&lt;br /&gt;&lt;br /&gt;Then in your form view, add an &#8216;error_for&#8217; call wherever you need one&#8230;&lt;br /&gt;&lt;br /&gt;&lt;code&gt;&lt;br /&gt;# _form.rhtml&lt;br /&gt;  &lt;p&gt;&lt;label for="code_project_name"&gt;Name&lt;/label&gt;&lt;br /&gt;  &lt;%= text_field &#8216;code_project&#8217;, &#8216;name&#8217;  %&gt;&lt;br /&gt;  &lt;%= error_for &#8216;code_project&#8217;, &#8216;name&#8217; %&gt;&lt;/p&gt;&lt;br /&gt;&lt;/code&gt;&lt;br /&gt;&lt;br /&gt;If the model fails a validation test, then it will show the message right next to the field that caused the validation problem.&lt;br /&gt;Also note that if you define an instance variable called @errors containing a hash of field_names and messages, they will also be used. This is handy for those form fields that don&#8217;t correspond to a model attribute.</description>
      <pubDate>Thu, 01 Feb 2007 14:06:27 GMT</pubDate>
      <guid>http://snippets.dzone.com/posts/show/3403</guid>
      <author>Mickael (Mickael)</author>
    </item>
    <item>
      <title>Active Record log</title>
      <link>http://snippets.dzone.com/posts/show/3402</link>
      <description>from &lt;http://weblog.jamisbuck.org/2007/1/31/more-on-watching-activerecord&gt;&lt;br /&gt;&lt;br /&gt;In config/environment.rb:&lt;br /&gt;&lt;br /&gt;&lt;code&gt;&lt;br /&gt;def log_to(stream)&lt;br /&gt;  ActiveRecord::Base.logger = Logger.new(stream)&lt;br /&gt;  ActiveRecord::Base.clear_active_connections!&lt;br /&gt;end&lt;br /&gt;&lt;/code&gt;&lt;br /&gt;&lt;br /&gt;then in the console :&lt;br /&gt;&lt;code&gt;&lt;br /&gt;&gt;&gt; log_to STDOUT&lt;br /&gt;=&gt; ...&lt;br /&gt;&gt;&gt; Post.find(:first)&lt;br /&gt;  Post Load (0.000138)   SELECT * FROM posts LIMIT 1&lt;br /&gt;=&gt; #&lt;Post:0x1234 ...&gt;&lt;br /&gt;&gt;&gt;&lt;br /&gt;&lt;/code&gt;&lt;br /&gt;&lt;br /&gt;The best part is, by clearing the active connections after setting the logger, you can change the logger at any time, even after you&#8217;ve made any number of find calls.&lt;br /&gt;&lt;br /&gt;And, you can pass your own stream objects into it:&lt;br /&gt;&lt;code&gt;&lt;br /&gt;&gt;&gt; buffer = StringIO.new&lt;br /&gt;=&gt; ...&lt;br /&gt;&gt;&gt; log_to buffer&lt;br /&gt;=&gt; ...&lt;br /&gt;&gt;&gt; Post.find(:first)&lt;br /&gt;=&gt; #&lt;Post:0x1234 ...&gt;&lt;br /&gt;&gt;&gt; p buffer.string&lt;br /&gt;=&gt; "  \e[4;35;1mPost Load (0.000138)\e[0m   \e[0mSELECT * FROM posts LIMIT 1\e[0m\n"&lt;br /&gt;&gt;&gt;&lt;br /&gt;&lt;/code&gt;</description>
      <pubDate>Thu, 01 Feb 2007 13:45:53 GMT</pubDate>
      <guid>http://snippets.dzone.com/posts/show/3402</guid>
      <author>Mickael (Mickael)</author>
    </item>
    <item>
      <title>Request Database Authentication</title>
      <link>http://snippets.dzone.com/posts/show/3389</link>
      <description>Simple solution to a problem that may not affect very many folks.&lt;br /&gt;If you don't like your password displayed in plain text in database.yml, this might help you.&lt;br /&gt;It utilizes the Highline gem (big thanks to James Edward Gray II).&lt;br /&gt;&lt;http://www.bigbold.com/snippets/posts/show/3361&gt;&lt;br /&gt;&lt;br /&gt;&lt;code&gt;&lt;br /&gt;# database.yml&lt;br /&gt;&lt;br /&gt;&lt;%&lt;br /&gt;require 'highline/import'&lt;br /&gt;&lt;br /&gt;def request_input(msg, show_input = true)&lt;br /&gt;  ask(msg) { |q| q.echo = show_input }&lt;br /&gt;end&lt;br /&gt;%&gt;&lt;br /&gt;&lt;br /&gt;#...&lt;br /&gt;  username: &lt;%= request_input 'Username: ' %&gt;&lt;br /&gt;  password: &lt;%= request_input 'Password: ', false %&gt;&lt;br /&gt;#...&lt;br /&gt;&lt;/code&gt;</description>
      <pubDate>Tue, 30 Jan 2007 13:52:26 GMT</pubDate>
      <guid>http://snippets.dzone.com/posts/show/3389</guid>
      <author>Mickael (Mickael)</author>
    </item>
    <item>
      <title>Rails mot reserve</title>
      <link>http://snippets.dzone.com/posts/show/3374</link>
      <description>Mot r&#233;serv&#233;s en rails&lt;br /&gt;&lt;code&gt;&lt;br /&gt;ruby -r config/environment -e 'print Object.constants.sort.join(", ")'&lt;br /&gt;&lt;/code&gt;</description>
      <pubDate>Fri, 26 Jan 2007 21:26:33 GMT</pubDate>
      <guid>http://snippets.dzone.com/posts/show/3374</guid>
      <author>Mickael (Mickael)</author>
    </item>
  </channel>
</rss>
