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

Duane Johnson http://blog.inquirylabs.com/

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

Transpose CSV Dataset Using FasterCSV

Takes a dataset such as:
   1  
   2   $10,000 	 $15,000 	 $20,000 
   3   $30,000 	 $35,000 	 $40,000 
   4  1	1	2
   5  1	1	2
   6  1	1	2
   7  2	2	2


and converts it to
   1  
   2  1000000,3000000,1,1,1,2
   3  1500000,3500000,1,1,1,2
   4  2000000,4000000,2,2,2,2


   1  
   2    def transpose_csv_fixture_file!(path)
   3      converter = proc{ |v| v =~ /\$/ ? v.gsub(/[$,]/, "").to_i * 100 : v.to_f }
   4      data = FasterCSV.read(path, :col_sep => "\t", :converters => converter ).transpose
   5      FasterCSV.open(path, "w") { |csv| data.each{ |line| csv << line } }
   6    end

Getting the _session_id from SWFUpload (Flash 8 multiple file uploader)

It appears that Ruby's CGI::Session class will not use the _session_id in the query string when the Request is a POST.

Normally, a POST-type request occurs when a form is submitted to the server (e.g. a Rails application). In this scenario, there is an easy workaround since we can send the _session_id as a hidden field.

With Flash 8, however, there is no way to add a 'hidden field' to the multi-part form data, thus Rails will fail to recognize the _session_id in the query string portion of our request.

Here is a hackish work-around:

   1  
   2  # The following code is a work-around for the
   3  # Flash 8 bug that prevents our multiple file uploader
   4  # from sending the _session_id.  Here, we hack the
   5  # Session#initialize method and force the session_id
   6  # to load from the query string via the request uri. 
   7  # (Tested on Lighttpd)
   8  
   9  class CGI::Session
  10    alias original_initialize initialize
  11    def initialize(request, option = {})
  12      session_key = option['session_key'] || '_session_id'
  13      option['session_id'] =
  14        request.env_table["REQUEST_URI"][0..-1].
  15        scan(/#{session_key}=(.*?)(&.*?)*$/).
  16        flatten.first
  17      original_initialize(request, option)
  18    end
  19  end

ActiveRecord::Errors#to_xml

Here’s a method that will allow you to call to_xml on an ActiveRecord::Errors object. We’re using this to pass errors between web apps via a web service api.

   1  
   2  class ActiveRecord::Errors
   3    def to_xml(options = {})
   4      options[:indent] ||= 2
   5      options.reverse_merge!({ :builder =>
   6        Builder::XmlMarkup.new(:indent =>
   7          options[:indent]), :root => "errors" })
   8      options[:builder].instruct! unless options.delete(:skip_instruct)
   9  
  10      options[:builder].__send__(options[:root].to_s.dasherize) do |xml|
  11        @errors.each do |key, value|
  12          xml.__send__(key.to_s.dasherize) do |xm|
  13            for message in value
  14              xm.message(message)
  15            end
  16          end
  17        end
  18      end
  19  
  20    end
  21  end

Validate URIs by Pinging the Server

   1  
   2  require 'open-uri'
   3  
   4  class ActiveRecord::Base
   5    def self.validates_uri_existence_of(*attr_names)
   6      configuration = { :message => "is not a valid web address" }
   7      configuration.update(attr_names.pop) if attr_names.last.is_a?(Hash)
   8      validates_each attr_names do |m, a, v|
   9        begin
  10          # Try to open the URI
  11          open v
  12        rescue
  13          # Report the error if it throws an exception
  14          m.errors.add(a, configuration[:message])
  15        end
  16      end
  17    end
  18  end


Details on my blog.

Use background color to show error fields instead of wrapping them in a div

Using the default rails field_error_proc may lead to some layout headaches--your form looks perfect until, uh-oh, someone entered an invalid email address and Rails adds a fieldWithError-styled div that wraps around the problem field.

While this works in many cases, some pixel-perfect layouts may not be able to tolerate the 2-pixel padding around the text_field caused by the red border. An alternative is to change the background color of the offending field.

Include the following code in environment.rb (or use a "require" like I do):

   1  
   2  ActionView::Base.field_error_proc = Proc.new do |html_tag, instance|
   3    error_style = "background-color: #ffff80"
   4    if html_tag =~ /<(input|textarea|select)[^>]+style=/
   5      style_attribute = html_tag =~ /style=['"]/
   6      html_tag.insert(style_attribute + 7, "#{error_style}; ")
   7    elsif html_tag =~ /<(input|textarea|select)/
   8      first_whitespace = html_tag =~ /\s/
   9      html_tag[first_whitespace] = " style='#{error_style}' "
  10    end
  11    html_tag
  12  end


See my blog.inquirylabs.com for more Rails stuff.

content_tag that accepts a block = block_tag

Sometimes I want to do something like this:

   1  
   2  <% content_tag("div", :class => "section_with_error" do %>
   3    HTML GOES HERE
   4  <% end %>


instead of this:

   1  
   2  <%= content_tag("div", "HTML GOES HERE", :class => "section_with_error") %>


Put the following code in ApplicationHelper, and you can do just that (replacing "content_tag" in the example above with "block_tag", of course):

   1  
   2    def block_tag(tag, options = {}, &block)
   3      concat(content_tag(tag, capture(&block), options), block.binding)
   4    end

String#to_id

Convert any (English) text to a programming-language friendly identifier.

   1  
   2  class String
   3    def to_id
   4      downcase.gsub(/\W+/, ' ').strip.gsub(' ', '_')
   5    end
   6   
   7    def to_id!
   8      replace to_id
   9    end
  10  end

Parse Technorati-style Tags from HTML

An enhancement to the String class that parses out Technorati-style tags. Uses Typo's strip_html method to remove img tags and other markup.

   1  
   2  class String
   3    # Strips any html markup from a string
   4    TYPO_TAG_KEY = TYPO_ATTRIBUTE_KEY = /[\w:_-]+/
   5    TYPO_ATTRIBUTE_VALUE = /(?:[A-Za-z0-9]+|(?:'[^']*?'|"[^"]*?"))/
   6    TYPO_ATTRIBUTE = /(?:#{TYPO_ATTRIBUTE_KEY}(?:\s*=\s*#{TYPO_ATTRIBUTE_VALUE})?)/
   7    TYPO_ATTRIBUTES = /(?:#{TYPO_ATTRIBUTE}(?:\s+#{TYPO_ATTRIBUTE})*)/
   8    TAG = %r{<[!/?\[]?(?:#{TYPO_TAG_KEY}|--)(?:\s+#{TYPO_ATTRIBUTES})?\s*(?:[!/?\]]+|--)?>}
   9    def strip_html
  10      self.gsub(TAG, '').gsub(/\s+/, ' ').strip
  11    end
  12  
  13    def tags
  14      scan(/<a\s+[^>]*\s*rel=\s*(.?)tag\1[^>]*>(.+?)<\/a>/i).
  15      map { |match| match.last.strip_html rescue nil }.
  16      compact.select { |s| !s.strip.empty? }
  17    end
  18  end
  19  
  20  # Example usage
  21  
  22  s = %{<a href="http://www.docstrangelove.com/tag/civil-war" rel="tag">civil war</a> <a href="http://www.technorati.com/tag/civil+war" rel="tag"><img src="http://www.docstrangelove.com/wp-content/plugins/UltimateTagWarrior/technoratiicon.jpg" alt="Technorati tag page for civil war"/></a> <a href="http://www.docstrangelovecom/tag/iraq" rel="tag">iraq</a> <a href="http://www.technorati.com/tag/iraq" rel="tag"><img src="http://www.docstrangelove.com/wp-content/plugins/UltimateTagWarrior/technoratiicon.jpg" alt="Technorati tag page for iraq"/></a>}
  23  
  24  s.tags
  25  # => ["civil war", "iraq"]

Array#randomly_pick( n )

Adds a handy function that lets you randomly pick n elements from an array.

   1  
   2  class Array
   3    # If +number+ is greater than the size of the array, the method
   4    # will simply return the array itself sorted randomly
   5    def randomly_pick(number)
   6      sort_by{ rand }.slice(0...number)
   7    end
   8  end

Firing a controller's action from the console

It seems like a simple task, but here's how you can simulate the calling of a controller's action:

   1  
   2  ruby script/console
   3  
   4  irb> require 'action_controller/test_process'
   5  irb> require 'application'
   6  irb> require 'site_controller'
   7  irb> request = ActionController::TestRequest.new
   8  irb> response = ActionController::TestResponse.new
   9  irb> request.env['REQUEST_METHOD'] = 'GET'
  10  irb> request.action = "late_employee"
  11  irb> InfoController.process(request,response)


Basically, it's like getting inside of a TestUnit method, but you have to do the dirty work yourself.
« Newer Snippets
Older Snippets »
Showing 1-10 of 14 total  RSS