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!)

About this user

« Newer Snippets
Older Snippets »
31 total  XML / RSS feed 

writing destructive string methods in Ruby

Use string class' method "replace" to overwrite its "self" value.

Example:

  def decapitalize!
    replace (self.reverse.chop + self.reverse.last.downcase).reverse
  end
  
  def decapitalize
    dup.decapitalize!
  end

Two or more parameters in RESTful route

Regardless of whether this is RESTful, to add multiple parameters to a normally RESTful route use the following

myresource_path(:id => myId, :extra_param => extraId, :extra_param2 => blah)


Results in
myresource/myId?extra_param=extraId&extra_param2=blah


See this Google Rails Group thread from Jeremy Kemper.

SOAP4R Rails NameError FIX

// description of your code here

Update /Library/Ruby/Gems/1.8/gems/soap4r-1.5.8/lib/soap
  # KNOWN_TAG = XSD::NS::KNOWN_TAG.dup.update(
  #   SOAP::EnvelopeNamespace => 'env'
  # ) # Replaced with code from http://dev.ctor.org/soap4r/ticket/433
  KNOWN_TAG = {
      XSD::Namespace => 'xsd', XSD::InstanceNamespace => 'xsi', SOAP::EnvelopeNamespace => 'env'
  }

Freeze rails

Freeze rails 1.2.3 to a project through rubyonrails.org TRAC.

rake rails:freeze:edge TAG=rel_1-2-3

old deprecated legacy plugins repository for Rails

// description of your code here

Find old official rails trunk plugins that didn't make the cut here:

http://dev.rubyonrails.org/svn/rails/plugins/legacy/

rails console - add module methods

Extend the functionality of the rails console by mixing in modules

>> extend ERB::Util
=> #
>> h('blahblah')
=> "<b>blahblah</b>"


You can extend ActionView::Helpers, etc. with this to provide view method functionality in the console.

http://errtheblog.com/post/43

eliminate duplicate flash on before_filter methods

When using a before filter to prevent unauthorized access to methods, use flash.now instead of flash, when painting error messages.

flash.now[:warning] = "You must be the group admin (and logged in) to edit."


see KerryBuckley.com for more info

ruby_inline permission denied when starting mongrel_cluster from init.d

The cause is the project is trying to read /root/.ruby_inline/Inline_ImageScience_aa58.c, yet the user running the rails project is the one specified in the /config/mongrel_cluster.yml (usually some other user that is NOT root).

When the project references anything to do with ImageScience, it will complain that it has insufficient rights to read the c library file, of course, since it's in root's home dir.

Solution, specify a home environment variable in your rails project's production.rb file (/rails_project/config/environments/production.rb)

ENV['HOME'] = '/home/billy'


Now when the project is started from system boot, or manually by calling ./etc/init.d/mongrel_cluster start, the rails project will always look to the user's home directory, rather than root's.

EDIT:

Or better yet, use this patch to lib/mongrel/configurator.rb
(was posted at ruby-on-rails talk google groups)
-          log "Changing user to #{user}." 
-          Process::UID.change_privilege(Etc.getpwnam(user).uid)
+          log "Changing user to #{user}."
+          getpwnam = Etc.getpwnam(user)
+          Process::UID.change_privilege(getpwnam.uid)
+          ENV['HOME'] = getpwnam.dir

Rotate Rails Log files

// description of your code here
Keeps 50 files of a maximum size of 5MB each

config.logger = Logger.new("#{RAILS_ROOT}/log/#{ENV['RAILS_ENV']}.log", 50, 5242880)

field focus in rails template

Stick the following in application_helper.rb:

def set_focus_to_id(id)
  javascript_tag("$('#{id}').focus()");
end


Then this in the templates as needed to generate a javascript focus tag.
(Note this exaple pretends to set focus for a field with id='user_login').
<%= set_focus_to_id 'user_login' %>

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| } 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
« Newer Snippets
Older Snippets »
31 total  XML / RSS feed