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

Mickael

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

Add rails log to console

In order to show rails log in console, add theses lines to your .irbrc

if ENV.include?('RAILS_ENV')&& !Object.const_defined?('RAILS_DEFAULT_LOGGER')
  Object.const_set('RAILS_DEFAULT_LOGGER', Logger.new(SDTOUT))
end

Converting Mysql Tables in InnoDB

// description of your code here

class ConvertMysqlToInnodb < ActiveRecord::Migration
 def self.up
   config = ActiveRecord::Base.configurations
   begin
     STDERR.puts "Migrating all existing tables to InnoDB"
     schema = []
     select_all('SHOW TABLES').inject([]) do |schema, table|
       schema << "ALTER TABLE #{table.to_a.first.last} ENGINE=InnoDB"
     end
     schema.each { |line| execute line }
   end if config[RAILS_ENV]['adapter'] == 'mysql' unless $schema_generator
 end
source http://trac.typosphere.org/browser/trunk/db/migrate/015_convert_mysql_to_innodb.rb

 def self.down
   # don't do anything
   # this is a one-way migration, but it's not "irreversable"
   # because it doesn't change any code logic
 end
end

Generate random password in ruby

Aaron Blohowiak suggests adding this as a public method in user.rb:


def new_random_password
  self.password= Digest::SHA1.hexdigest("--#{Time.now.to_s}--#{login}--")[0,6]
  self.password_confirmation = self.password
end

Init rails project script

From http://vinsol.com/2007/02/08/ruby-script-for-creating-new-rails-project-and-initial-svn-import-with-ignoringremoving-logother-files

require 'fileutils'

puts  "########################################"
puts  "This script creates a new rails project and do the initial svn import with ignoring/deleting files from subversion"
puts  "Please send your feedback to Akhil Bansal<bansalakhil30.10@gmail.com>"
puts  "I have tested this script and it works great on my system."
puts  ""
puts  ""
puts  "                    ###### ATTENTION #######"
puts  ""
puts  ""
puts  "Use this script at your own risk, if your computer explodes its not my fault :-) "
puts  "#######################################"

puts  "Enter svn username: "
username = gets.strip
puts  "Enter the svn url: "
svn_url =gets.strip

puts  "Enter Rails Application Path:(eg: /home/akhil/ror): "
app_path = gets.strip
puts  "Enter Application Name: "
app_name = gets.strip

puts  "######################################"


puts  "Please verify the following variables: "
puts  "Svn Username: #{username}"
puts  "Svn URL: #{svn_url}"
puts  "Application Path: #{app_path}"
puts  "Application name: #{app_name}"

puts  "Proceed (y/n)"
proceed = gets
proceed = proceed.strip.upcase
if proceed == 'N' 
    puts  "Terminating..."
    exit 0
elsif proceed == 'Y' 
    if system("rails -v")
      s="/"
    elsif   system("rails.cmd -v")
      s="\\"
    else
        puts "Cannot find rails. Terminating..."
        exit 0
    end    
    app_root=app_path+s+ app_name
    
    puts  "Generating rails project: (#{app_root})"
    if system("rails #{app_root}")
      s="/"
    elsif   system("rails.cmd #{app_root}")
      s="\\"
    else
        puts "Cannot create rails project. Terminating..."
        exit 0
    end    
    
    puts  "SVNinitial import: "
    system("svn import #{app_root} #{svn_url} -m \"Initial Import\" --username #{username}")
   
    FileUtils.remove_dir(app_root, true)
   
    puts  "Checking out from svn: "

    system("svn checkout #{svn_url} #{app_root}")
    FileUtils.cd(app_root, :verbose => true)
    
    puts  "Removing all log files from SVN"
    system("svn remove log"+s+"*")
    puts  "commiting..."
    system("svn commit -m \"removing all log files from subversion \" ")
    puts  "Ignoring all log files under log dir"
    system("svn propset svn:ignore \"*.log\" log"+s)
    puts  "Updating and commiting..."
    system("svn update log"+s)
    system("svn commit -m \"Ignoring all files in "+s+"log"+s+" ending in .log \" ")
    puts  "Removing tmp directory from SVN"
    system("svn remove tmp"+s)
    puts  "commiting..."
    system("svn commit -m \"removing the temp directory from subversion \" ")
    puts  "Ignoring tmp dir"
    system("svn propset svn:ignore \"*\" tmp"+s)
    puts  "Updating and commiting again...."

    system("svn update tmp"+s)
    system("svn commit -m \"Ignore the whole tmp"+s+" directory, might not work on subdirectories? \" ")
    puts  "Moving database.yml to database.example"
    system("svn move config"+s+"database.yml config"+s+"database.example")
    puts  "commiting..."
    system("svn commit -m \"Moving database.yml to database.example to provide a template for anyone who checks out the code \" ")
    puts  "Ignoring database.yml , updating and commiting..."
    system("svn propset svn:ignore 'database.yml' config"+s)
    system("svn update config"+s)
    system("svn commit -m \"Ignoring database.yml\" ")
    puts  "Finished."

else
    puts  "Unknown Input. Terminating..."
	exit 0
end

Putting the errors in the right place

The idea is to display the error near the field instead of in global area at the top of the page.
Simple… first go into your view and delete the
error_messages_forobject’


Then stick this in your application helper.


# application_helper.rb
def error_for(object, method = nil, options={})
if method
err = instance_variable_get("@#{object}").errors.on(method).to_sentence rescue instance_variable_get("@#{object}").errors.on(method)
else
err = @errors["#{object}"] rescue nil
end
options.merge!(:class=>’fieldWithErrors’,
:id=>"#{[object,method].compact.join(’_')}-error",
:style=>(err ? #{options[:style]}":"#{options[:style]};display: none;")
)
content_tag("p",err || "", options )
end


Then in your form view, add an ‘error_for’ call wherever you need one…

# _form.rhtml
  <p><label for="code_project_name">Name</label>
  <%= text_field ‘code_project’, ‘name’  %>
  <%= error_for ‘code_project’, ‘name’ %></p>


If the model fails a validation test, then it will show the message right next to the field that caused the validation problem.
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’t correspond to a model attribute.

Active Record log

from <http://weblog.jamisbuck.org/2007/1/31/more-on-watching-activerecord>

In config/environment.rb:

def log_to(stream)
  ActiveRecord::Base.logger = Logger.new(stream)
  ActiveRecord::Base.clear_active_connections!
end


then in the console :
>> log_to STDOUT
=> ...
>> Post.find(:first)
  Post Load (0.000138)   SELECT * FROM posts LIMIT 1
=> #<Post:0x1234 ...>
>>


The best part is, by clearing the active connections after setting the logger, you can change the logger at any time, even after you’ve made any number of find calls.

And, you can pass your own stream objects into it:
>> buffer = StringIO.new
=> ...
>> log_to buffer
=> ...
>> Post.find(:first)
=> #<Post:0x1234 ...>
>> p buffer.string
=> "  \e[4;35;1mPost Load (0.000138)\e[0m   \e[0mSELECT * FROM posts LIMIT 1\e[0m\n"
>>

Request Database Authentication

Simple solution to a problem that may not affect very many folks.
If you don't like your password displayed in plain text in database.yml, this might help you.
It utilizes the Highline gem (big thanks to James Edward Gray II).
<http://www.bigbold.com/snippets/posts/show/3361>

# database.yml

<%
require 'highline/import'

def request_input(msg, show_input = true)
  ask(msg) { |q| q.echo = show_input }
end
%>

#...
  username: <%= request_input 'Username: ' %>
  password: <%= request_input 'Password: ', false %>
#...

Rails mot reserve

Mot réservés en rails
ruby -r config/environment -e 'print Object.constants.sort.join(", ")'

Paginate over a collection (Array or Hash)

Sometimes could happen that we need to paginate something different from a collection, I found this very useful method that acts similar to a paginate but it works for Arrays ( and Hashes )

  def paginate_collection(collection, options = {})
    default_options = {:per_page => 10, :page => 1}
    options = default_options.merge options

    pages = Paginator.new self, collection.size, options[:per_page], options[:page]
    first = pages.current.offset
    last = [first + options[:per_page], collection.size].min
    slice = collection[first...last]
    return [pages, slice]
  end

Start rails dev env

Here's the script I use to start up my Rails editing environment. It assumes you are in the RAILS_ROOT folder, and you have textmate and mongrel.

#!/bin/sh
killall ruby
mongrel_rails start -d
sleep 1
open http://localhost:3000/
sleep 1
mate .
« Newer Snippets
Older Snippets »
Showing 1-10 of 10 total  RSS