Never been to CodeSnippets 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 (or not, you can keep them private!)

About this user

http://installingcats.com

request variables

Accessing request object environment variables is done through the 'env' hash.

Example: HTTP_USER_AGENT
request.env["HTTP_USER_AGENT"]

returns the browser's user_agent setting

AJAX multiple updates to calling page without using RJS template

When a controller action is called via XHR (XmlHttpRequest), the action will look for a .rjs template first, then a .rhtml template if not available.

To skip using the .rjs template, include a render(:update) {|page| <block code> } call to perform updates.

  def toggle_showall
    render(:update) do |page|
      page[:fb_content].replace_html "just text? ripoff!"
      page[:flash_box].visual_effect :blind_down, :duration => 0.25
    end
  end


We use page as a hash to reference elements by id from the originating page.

page[:fb_content]


Then perform the updates to the element. Here we're replacing the contents of the element with id of "fb_content" with the string of text.
page[:fb_content].replace_html "just text? ripoff!"


You can render anything you could normally using a render call, example, some partial.
page[:fb_content].replace_html :partial => "shared/some_partial"


If the partial you're calling has instance vars you need to fill before, just include them before the render(:update) block and they'll be available to the partial during rendering.


Here we execute scriptaculous' Effect.BlindDown on element 'flash_box' with option of duration of .25 seconds.
page[:flash_box].visual_effect :blind_down, :duration => 0.25


There are plenty of other methods you can call on a page element. Refer to the Agile WebDev PDF for more details.

Using ActionView helpers in Controllers and elsewhere

Yup, let's break some MVC conventions...

Within your controller
include ActionView::Helpers::DateHelper


to get access to any of the methods within that module.

This mixes in the methods from the module right into the controller so there's no need for qualifying calls to methods.

Multiple updates to calling page in AJAX call

Uses Rails' .rjs template to form multiple update calls, server side, that will update the calling page with the included javascript.

Example:

def original_control_handler
 [misc methods and other things]
 [done normally in this controller]
 render :update do |page|
  page.replace_html 'calling_element_id', :partial => 'updated_template'
  page.helper 'helper_id', :helper_options => 'go here'
 end
end


Without rjs templates, you would have to write complex javascript by hand to update multiple elements on the calling page after returning from an XMLHTTPREQUEST (XHR) request. This allows you to avoid that, and do it all server side.

You can also place the update calls into an actual view templates instead of in the controller. Just put the contents of the update block into app/views/[controller]/original_control_handler

To replace simple tag contents, just provide a string of what to replace it with
 ...
 page.replace_html 'element_to_update', "this string goes in element"


Or replace the entire tag itself.
 page.replace 'element2_to_update', 
  (link_to_remote "link_text", {:url => dest, :method => :get, :id => 'element2_to_update')



Building :with querystring values in AJAX remote_function call

To build the string with multiple values, you must end it with an '=' char.

example:
To get this
?chapter=9&sort_by=created_at&sort_dir=desc


You need this
:with => "'chapter='+ encodeURIComponent(value)+'&sort_by=#{@sort_by}&sort_dir=#{@sort_dir}&='", :update => 'list_items'


Explained at: http://codefluency.com/2006/6/2/rails-views-using-the-with-option

AJAX link submit of form

Submit a form using a link, which itself shows different text depending on whether a database item exists or not.

Place this in .rhtml file (or layout file for site-wide coverage)
<%= javascript_include_tag "prototype" %>


Creates a link that fires a javascript method.
Method is created by remote_function.
Form.Serialize processes the entire form contents into a string so that receiving page is none the wiser.
Giving link an id ('follow_anchor') and asking remote_function to update the same id, allows us to dynamically change the innerHTML of the link. On the target side, have the method (create in this case) render text that will be used as the new innerHTML of this link.
<%= link_to_function @toggle_text, remote_function(:url => watch_lists_path, :method => :post, :with => "Form.serialize('watch_form')", :update => 'follow_anchor'), :id => 'follow_anchor' %>


  def create
    @watch_list = WatchList.new(params[:watch_list])

    if @watch_list.toggle
      render(:text => @watch_list.toggle_text)
    else
      render(:text => 'We couldn''t add this book to your Watch List. Please contact us for help.')
    end
  end




printing debug information in development mode in Rails

// description of your code here

logger = Logger.new(STDOUT)
logger.debug ("title: #{@attr.get('title')}")
logger.debug("small_image: #{@images.search_and_convert('smallimage')}")

debug print Hpricot xml object

// description of your code here

debug(@instance_var.pretty_inspect)

/tmp/mysql.sock file not found

first finds where your .sock file is

second sets a symbolic link to the sock so Rails' default location for the sock is cool

mysql_config --socket

sudo ln -s  /var/run/mysqld/mysqld.sock /tmp/mysql.sock

one rails app, multiple domains (via alias domains)

Short version:
Is there any problem with serving a rails app from multiple domain names by simply creating an Alias Server and adding another $HTTP["host"] entry to your rails/lighttpd conf file (in ~/etc/lighttpd/vhosts.d/APPNAME.conf)?

Long version:
Here's the deal:
on the default virtual server created when you purchase a shared webhosting plan (USERNAME.textdrive.com) I've got a rails app installed and running off of fcgi.

Here's the .conf file for my particular rails app that gets included into the main lighttpd.conf file:

$HTTP["host"] =~ "(www\.)?(hatepad|sexymsg)\.(com|net)" {
  server.document-root        = base + "/domains/sexymsg.com/web/public/"
  server.error-handler-404 = "/dispatch.fcgi"
  fastcgi.server = (
        ".fcgi" => ( "localhost" => ( "socket" => base + "/var/run/sexymsg-0.socket" ) )
        )
}



After that, simply kill and restart the lighttpd process
kill -9 <lighttpd PID>
. ~/etc/rc.d/lighttpd.sh start