Never been to TextSnippets 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!)

« Newer Snippets
Older Snippets »
Showing 21-40 of 125 total

request variables

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


returns the browser's user_agent setting

sample of dutch validation error messages

//Dutch validation error messages
//Put this at the end of environment.rb

module ActiveRecord
  class Errors
      @@default_error_messages = {
        :empty => "dient verplicht ingevuld te worden",
        :blank => "dient verplicht ingevuld te worden",

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| } 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

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


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.


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'

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.

To get this

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

Explained at:

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 =[:watch_list])

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

printing debug information in development mode in Rails

// description of your code here

logger =
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


/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 ( 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/"
  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/ start

Wraps a block of content in an html tag, only if it has content present

Fed up of empty wrapper html tags when content isn't there? Then use this Rails helper...

  def tag_unless_empty(html_tag, options = {}, &block)
    html_options = options.stringify_keys

    if block_given?
      content = capture(&block)
      unless content.strip.empty?
        concat(tag(html_tag, html_options, true), block.binding)
        concat(content, block.binding)
        concat("#{html_tag}>", block.binding)


<% tag_unless_empty :div, :class => "css_class" do %>
   <%# Nothing actually rendered here %>
   <%# or here %>
<% end %>

produces nothing, whereas

<% tag_unless_empty :div, :class => "css_class" do %>
   <%= 'Something rendered here' %>
<% end %>


<div class="css_class">Something rendered herediv>

Plugin: Attachment_fu - Install, Setup, Testing

This nightmare has required the following:

- Add
ENV[‘DB’] =mysql’
to /config/environment.rb
- Add:
rescue Technoweenie::AttachmentFu::Backends::S3Backend::RequiredLibraryNotFoundError
to /vendor/plugins/attachment_fu/test/fixtures
- Go into ../test and run: ruby test_helper.rb
- if all goes well you should finish the test_helper load without error.
- delete the file backends/remote/s3_test.rb (useless tests of S3 system)

Attached is a generators directory that should go under the base directory of attachment_fu/
This can be used as a model generator for models using a_fu. Use scaffold_resource generator after attachment_model to generate a skeleton site upon which to build.

Restful Authentication - Check User admin status

Uses h_a_b_t_m relationship to Tier table (via tiers_users join table) to return an array of access groups this user is a member of.

def is_admin? #TODO: make into an accessor?
        return false unless self.tiers
        tier_names = self.tiers.collect {|t|}
        return tier_names.include? "admin"

Uninitialized constant error in Rails migration

This was because I had pluralized Tiers in its class definition, not because Rails was acting different. The below is not true, but it still is a good idea because if you change any models in the future, it will break subsequent migrations (which would likely happen anyways)

Now for some reason you have to define your models within your migration to get access to their functionality. It's not guaranteed that the migration will have automatic access to your models.

class LoadTiersUsers < ActiveRecord::Migration
  extend MigrationHelpers

        class Tier < ActiveRecord::Base; has_and_belongs_to_many :users end
        class User < ActiveRecord::Base; has_and_belongs_to_many :tiers end
        class TiersUsers < ActiveRecord::Base; end
  def self.up
                p "*** Loading user, tier data..."

Loop Through Flash Messages

In your layout, you can loop through all flash messages.

Instead of putting a separate declaration for each :flash type like this:

<% unless flash[:notice].nil? %>
><%= flash[:notice] %>
<% end %> <% unless flash[:error].nil? %>
="notice"><%= flash[:error] %>
<% end %> ... etc.

You can loop through all flash messages at once like this:

<% flash.each do |key, msg| %>
  <%= content_tag :div, msg, :id => key %>
<% end %>

(via Railscasts)

Manually adding REST route

This named route handles urls such as:
which would route to controller => 'tags', :tag => 'wicked'
while creating named routes tag_path and tag_url.
The singular naming method keeps inline with REST conventions in Rails.
map.tag 'tags/:tag', :controller => 'tags', :action => 'show', :conditions => {:method => :get}

rendering layout from different controller

If an action in one controller leads to a deadly similar template as in another controller, you can just borrow that controller's action template by calling render at the end of your action.
render :template => ''

Say your in tags controller in the show action. You can use the template found in /apps/views/lists/index.rhtml
def show
  [boring action logic]
  render :template => 'lists/index'

default layout for a controller

// description of your code here
In your controller add the name of the .rhtml file in /apps/layouts/ that you want to use, without the suffix (.rhtml).
When rails spits out your view, it will use this given layout as the container for your rendered action.
layout ""

Acts as Taggable on Steroids: tag cloud rhtml + view helper

// description of your code here
controller layout (base) stylesheet update
  <%= stylesheet_link_tag 'scaffold', 'tag_cloud' %>

create stylesheet, put it in ./public/, name it tag_cloud.css or similar
/* tag_cloud styles*/
.nube1 {font-size: 1.0em;}
.nube2 {font-size: 1.2em;}
.nube3 {font-size: 1.4em;}
.nube4 {font-size: 1.6em;}
.nube5 {font-size: 1.8em;}
.nube6 {font-size: 2.0em;}

partial template call
        TAG CLOUD<br/>
        <%= render(:partial => "shared/article_tag_cloud", :locals => {:tags => @tags}) %>

view template code, as a partial or within index/show action template
        <% # For our purposes, have this filter the list of articles to those with the chosen tag
                tag_cloud true, tags, %w(nube1 nube2 nube3 nube4 nube5) do |name, css_class| %>
                <%= link_to name, tag_path(name), class => css_class # links to Tag resource, with tag name as 'id'
        <% end %>

helper code
        def tag_cloud(active, tags, classes)
                if !active then return end
                max, min = 0, 0
                unless tags.empty?
                        tags.sort! {|x,y| y.count <=> x.count}
                        max = tags.first.count
                        min = tags.last.count                      
                divisor = ((max - min) / classes.size) + 1
                tags.each { |t|
                        yield, classes[(t.count.to_i - min) / divisor]
« Newer Snippets
Older Snippets »
Showing 21-40 of 125 total