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

Barry Hess http://blog.bjhess.com

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

Rails-like number_to_currency currency formatting

This is pretty much a port of the Ruby on Rails number_to_currency method, right down to the hashed options.

number_to_currency: function (number, options) {
  try {
    var options   = options || {};
    var precision = options["precision"] || 2;
    var unit      = options["unit"] || "$";
    var separator = precision > 0 ? options["separator"] || "." : "";
    var delimiter = options["delimiter"] || ",";
  
    var parts = parseFloat(number).toFixed(precision).split('.');
    return unit + reports.number_with_delimiter(parts[0], delimiter) + separator + parts[1].toString();
  } catch(e) {
    return number
  }
},

number_with_delimiter: function (number, delimiter, separator) {
  try {
    var delimiter = delimiter || ",";
    var separator = separator || ".";
    
    var parts = number.toString().split('.');
    parts[0] = parts[0].replace(/(\d)(?=(\d\d\d)+(?!\d))/g, "$1" + delimiter);
    return parts.join(separator);
  } catch(e) {
    return number
  }
}

Migration to change all MySQL table engines to InnoDB

I have a database with an eclectic mix of table types/engines - almost random between MyISAM and InnoDB. I wanted to get transactional, so I wrote this migration to bring everything in line.

class ChangeTableTypes < ActiveRecord::Migration
  
  def self.up
    ActiveRecord::Migration::say 'Setting all tables to InnoDB engine (excluding schema_info table)...'
    result = ActiveRecord::Migration::execute 'show tables'
    while table = result.fetch_row
      execute("ALTER TABLE #{table.to_s} TYPE = InnoDB") unless table.to_s == 'schema_info'
    end
  end

  def self.down
    raise ActiveRecord::IrreversibleMigration
  end
end


Barry Hess

Rails auto select text field

A simple helper to create those snazzy on-click-auto-select text fields you see on all the video-sharing sites.

def auto_select_text_field_tag(name, value = nil, options = {})
  text_field_tag(name,
                 value,
                 { :onclick => "$(’#{name}’).select()",
                   :readonly => "true" }.merge(options))
end



A _little_ more info on my blog.

~Barry Hess
« Newer Snippets
Older Snippets »
Showing 1-3 of 3 total  RSS