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-4 of 4 total  RSS 

Add a Google custom search facility to your website

This HTML page displays a basic search page similar to http://www.google.com/ however this search page will only search for results from http://snippets.dzone.com.

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
    "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en"><head>
<title>abc</title>
<meta http-equiv="Content-Type" content="text/html; charset: UTF-8" />

</head>
<body>

    <form action="http://www.google.com/search">
      <div><input name="query" type="hidden" value="site:snippets.dzone.com"></input></div>
      <div><input maxlength="2048" name="q" size="55" title="Google Search" value="" ></input></div>
      <div><input name="btnG" type="submit" value="Google Search"></input></div>
    </form>
</body>
</html>

I stumbled across the hidden query field while I was looking for ways to perform custom search without the need for JavaScript. If you are interested in Google's official custom search engine on your site go to http://www.google.com/cse

* update 8-Jan-08 2:01pm *
Here's a more advanced example from someone's blog titled 'Fine-tuning Custom Google Search' http://snipr.com/1wppb [blogs.salon.com]
<FORM method=GET action=http://www.google.com/custom>;
<A HREF=http://www.google.com/search>;
<IMG SRC=http://www.google.com/logos/Logo_40wht.gif border=0 ALT=Google align=middle></A> <INPUT TYPE=text name=q size="10" maxlength=255 value="">
<INPUT type=submit name=sa VALUE="Just Goog It!">
<INPUT type=hidden name=cof VALUE="GIMP:darkblue;LW:380;ALC:red;L:http://blogs.salon.com/0001111/images/rfbanner.jpg;GFNT:lightblue;LC:red;LH:100;AH:left;VLC:gray;S:http://blogs.salon.com/0001111/;GALT:blue;AWFID:ba6ecf243ae3d16f;"><br />
>span class="small">
<input type=radio name=sitesearch value="blogs.salon.com" checked>Search blogs.salon.com
<input type=radio name=sitesearch value="">Search the Web</span><br />
</FORM>

Using helpers inside a controller

Ripped from
http://gabriel.gironda.org/articles/2006/02/08/using-helpers-inside-a-controller


This is incredibly straightforward and more of an occasional convenience, but I thought I'd throw it out there anyway. You may find that sometimes, even though the controller obviously isn't the view, that you want to use some of the helper methods available.

The only case I've come across so far is wanting to use pluralize() in a flash message and not have to do it by hand using the inflector. You could include ActionView::Helpers::TextHelper in the controller, but that fills your namespace with crap.

Put this in the class ApplicationController instead:

  def help
    Helper.instance
  end

  class Helper
    include Singleton
    include ActionView::Helpers::TextHelper
  end


Then you can just use it like so:

  def check_for_max_donkeys
    if Donkey.find_fit_donkeys.size == APP_SETTINGS['max_fit_donkeys']
      flash_error "The maximum of #{help.pluralize(APP_SETTINGS['max_fit_donkeys'], 'donkey')} has been reached."
      redirect_to_index
    end
  end


Update: Don't use the method name "helper" because Rails already uses that. Just "help" works fine.

Validations for Non-ActiveRecord Objects

I needed to find a way to use active record validations on non active record items so i went searching and found this blog which is useful for me..
Totally ripped off Peter Donald's blog :P
http://www.realityforge.org/articles/2005/12/02/validations-for-non-activerecord-model-objects

To get this working grab the active_form.rb file and place it in the app/models directory. You can then make your model objects extend ActiveForm and use them like regular ActiveRecord objects.

active_form.rb
# Note ".valid?" method  must occur on object for validates_associated
class ActiveForm
  
  def initialize(attributes = nil)
    if attributes
      attributes.each do |key,value|
        send(key.to_s + '=', value)
      end
    end
    yield self if block_given?
  end

  def [](key)
    instance_variable_get("@#{key}")
  end

  def method_missing( method_id, *args )
    if md = /_before_type_cast$/.match(method_id.to_s)
      attr_name = md.pre_match
      return self[attr_name] if self.respond_to?(attr_name)
    end
    super
  end

protected 
  def raise_not_implemented_error(*params)
    ValidatingModel.raise_not_implemented_error(*params)
  end

  def self.human_attribute_name(attribute_key_name)
    attribute_key_name.humanize
  end

  def new_record?
    true
  end

  # these methods must be defined before include
  alias save raise_not_implemented_error
  alias update_attribute raise_not_implemented_error

public
  include ActiveRecord::Validations

protected 

  # the following methods must be defined after include so that they overide
  # methods previously included
  alias save! raise_not_implemented_error

  class << self
    def raise_not_implemented_error(*params)
      raise NotImplementedError
    end

    alias validates_uniqueness_of raise_not_implemented_error
    alias create! raise_not_implemented_error
    alias validate_on_create raise_not_implemented_error
    alias validate_on_update raise_not_implemented_error
    alias save_with_validation raise_not_implemented_error    
  end
end

require 'dispatcher'
class Dispatcher
  class << self
    if ! method_defined?(:form_original_reset_application!) 
      alias :form_original_reset_application! :reset_application!
      def reset_application!
        form_original_reset_application!
        Dependencies.remove_subclasses_for(ActiveForm) if defined?(ActiveForm)
      end
    end
  end
end

Defining a custom validates in rails

in the model:

class User < ActiveRecord::Base
  require 'validations'

  validates_positive_or_zero :number
  
end


in /lib/validations.rb:

def validates_positive_or_zero(*attr_names)
  configuration = { :message => "Cannot be negative" }
  configuration.update(attr_names.pop) if attr_names.last.is_a?(Hash)
  validates_each attr_names do |m, a, v| m.errors.add(a, configuration[:message]) if v<0 end
end
« Newer Snippets
Older Snippets »
Showing 1-4 of 4 total  RSS