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

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

Tidy Remote HTML (using a web service)

// Clean up some code using a web service. If you need to do this more quickly I suggest using a local tidy installation
// rather than my web service, but this is nice and easy. :)

function tidied($url) {
  /* Cleans up a page via Tidy, returning the cleaned up html as a string
   * By Logan Koester <logan@logankoester.com> 2007-06-28
   * Props to http://infohound.net/tidy */
  return file_get_contents("http://logankoester.com/tools/tidy.php?q=$url");
}

How to parse a little language in Prolog

How to parse a token list into functors (structured terms) in Prolog.
The book "Logic in Prolog" by Gibbins has some good example code
See http://www.ddj.com/184404172, listing 9 for the little language
%
% This is a simple (nay,trivial!)  "dialect" 
% with only two commands.
 
% Obviously only scratches the surface - 
% Written as a learning exercise!
% First define a grammar using prolog's Definite 
% Clause Grammar (DCG) notation
% DCG is a bit like a macro system - 
% the grammar rules are expanded into
% ordinary prolog clauses  before execution:
% Thanks to prolog unification, the Cmd variable
% will end up being instantiated to a functor like
% sell(abc,10,5) or buy(xyz,55):

cmd(Cmd) --> sell,!,amount(Amount),of,stock(Stock),at,price(Price), 
             { Cmd = sell(Stock,Amount,Price) }.
cmd(Cmd) --> buy,!,amount(Amount),of,stock(Stock), 
             {Cmd = buy(Stock,Amount)}.
sell --> [sell].
of --> [of].
at --> [at].
buy --> [buy].
amount(Amount) --> [Amount].
stock(Stock)   --> [Stock].
price(Price)   --> [Price].

% mini-evaluator:

eval(sell(Stock,Amount,Price)) :- 
 format('Sold ~d ~a shares at $~d.~n',[Amount,Stock,Price]).
eval(buy(Stock,Amount)) :- 
 format('Bought ~d ~a shares.~n',[Amount,Stock]).

% parse a statement, if it's a command, 
% evaluate it, otherwise write an error
% (NB.  ";" is prolog's % "or".)

interp(Statement) :- cmd(Cmd,Statement,[]),
             eval(Cmd);write('Unrecognised command!').

% Examples: 
% ( First two match , the last fails.)

test :-
    interp([sell,100,of,xyx,at,50]),
    interp([buy,45,of,abc]),
    interp([not,accepted]).

Find every path and it's value in a Hash

Extends Hash class with each_path method.

This method takes a block as argument which is called each time a the recursivly searched Hash returns a key that does not point to another Hash.

Example:
paths = []
complex_hash = Hash[
  :a => { :aa => '1', :ab => '2' },
  :b => { :ba => '3', :bb => '4' }
]
complex_hash.each_path { |path, value| paths << [ path, value ] }
paths.inspect
# => "[[\"b/ba/\", \"3\"], [\"b/bb/\", \"4\"], [\"a/aa/\", \"1\"], [\"a/ab/\", \"2\"]]"


class Hash
  def each_path
    raise ArgumentError unless block_given?
    self.class.each_path( self ) { |path, object| yield path, object }
  end

  protected
  def self.each_path( object, path = '', &block )
    if object.is_a?( Hash ) then object.each do |key, value|
        self.each_path value, "#{ path }#{ key }/", &block
      end
    else yield path, object
    end
  end
end

SQL-Injection save parser generates ORDER BY statement

Parses a string and generates an SQL order statement.

Because it's SQL-Injection save you can put it in your link_to method as :order => '+name' and then call #parse_order( params[:order] ).

Examples:
'+name' => 'name'
'+lastname+firstname' => 'lastname, firstname'
'+lastname-gender' => 'lastname, gender DESC'

module ActiveRecord
  class Base
    class << self

      def parse_order( order )
        order = order.to_s.gsub /([ \+\-][a-z_]+)/ do |match|
          next unless self.column_names.include?( match[1..-1] )

          case match[0, 1]
          when '-' then "#{ match[1..-1] } DESC, "
          else "#{ match[1..-1] }, "
          end
        end and order[0..-3]
      end
    
    end
  end
end

Multi-part parameter extractor

For those times when you want to get a date object out of the multi-part parameters without having to do a mass assignment to a model object. I extracted this code directly from AR so I think it should be pretty solid but I have not tested it so your mileage may vary.

Take the following and place it into your application helper or whatever helper you'd like. To use it you simply pass in an instance of the object on which the multi-part parameter exists. This is so that the type to instantiate can be reflected from the column information. Then you specify the attribute name of the parameter you're looking to create from the next parameter which is the hash containing the multi-part parameter value.

example:
for a form containing dude[birth_date] you'd call the method like this:

extract_date(@the_dude, 'birth_date', params[:dude])

    def extract_date(parent_object, param_name, atts)
      atts.stringify_keys!

      multi_parameter_attributes = []
      atts.each do |k, v|
        multi_parameter_attributes << [ k, v ] if k.include?(param_name+"(")
      end
      
      attributes = { }

      for pair in multi_parameter_attributes
        multiparameter_name, value = pair
        attribute_name = multiparameter_name.split("(").first
        attributes[attribute_name] = [] unless attributes.include?(attribute_name)

        unless value.empty?
          attributes[attribute_name] <<
            [ find_parameter_position(multiparameter_name), type_cast_attribute_value(multiparameter_name, value) ]
        end
      end

      attributes.each { |name, values| attributes[name] = values.sort_by{ |v| v.first }.collect { |v| v.last } }
      errors = []
      result = nil
      attributes.each do |name, values|  
        klass = (parent_object.class.reflect_on_aggregation(name.to_sym) || parent_object.column_for_attribute(name)).klass
        result = Time == klass ? klass.local(*values) : klass.new(*values)
      end

      return result
    end
    
    def find_parameter_position(multiparameter_name)
      multiparameter_name.scan(/\(([0-9]*).*\)/).first.first
    end

    def type_cast_attribute_value(multiparameter_name, value)
      multiparameter_name =~ /\([0-9]*([a-z])\)/ ? value.send("to_" + $1) : value
    end
« Newer Snippets
Older Snippets »
Showing 1-5 of 5 total  RSS