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

Testing for nil or empty params in Ruby on Rails

I find myself doing these 4 things a lot:
if params[:object] && !params[:object].empty
if params[:object] && params[:object] == value
if params[:object][:attribute] && !params[:object][:attribute].empty
if params[:object][:attribute] && params[:object][:attribute] == value

I put params_check() in my application.rb and it allows me to do this instead:
if params_check(:object)
if params_check(:object, value)
if params_check([:object, :attribute])
if params_check([:object, :attribute], value)

  def params_check(*args)
    if args.length == 1
      if args[0].class == Array
        if params[args[0][0]][args[0][1]] && !params[args[0][0]][args[0][1]].empty?
          true
        end
      else        
        if params[args[0]] && !params[args[0]].empty?
          true
        end
      end
    elsif args.length == 2
      if args[0].class == Array
        if params[args[0][0]][args[0][1]] && params[args[0][0]][args[0][1]] == args[1]
          true
        end
      else
        if params[args[0]] && params[args[0]] == args[1]
          true
        end
      end  
    end
  end

I stole this off another snippet and modified it to add more conditions. Thanks to whoever it was.

Unify the handling of XML records

This Ruby code creates, updates or deletes an XML record, using a hash, record handling objects, and XML to invoke the correct method.

#file: recordx_handler.rb
require 'recordx'

class RecordX_Update < RecordX
  def call(params)
    #todo: write the code to read the xml parameter string
    update_record(h)
    save_file 
  end
end

class RecordX_Create < RecordX
  def call(params)
    #todo: write the code to read the xml parameter string  
    create_record(h)
  end
end

class RecordX_Delete < RecordX
  def call(params)
    doc = Document.new(params)
    node = doc.root.elements["param[@var='id']"]
    puts node
    id = node.attributes.get_attribute('val').to_s
    delete_record(id)
    puts 'deleted record ' + id
    save_file
  end
end

class RecordX_handler
  def invoke(method, params)
    h = Hash.new
    h["create"] = RecordX_Create.new
    h["update"] = RecordX_Update.new
    h["delete"] = RecordX_Delete.new
    h[method].call(params)
  end
end

if __FILE__ == $0
  xml_method = "<method name='delete'><params><param var='id' val='17648' /></params></method>"
  doc = Document.new(xml_method)
  method = doc.root.attributes.get_attribute('name').to_s
  params = doc.root.elements['params'].to_s

  rh = RecordX_handler.new
  rh.invoke(method, params)
end


This code is intended to be called by a Ruby CGI script which can simply relay the cgi post argument to the recordx_handler object.

Hash Tricks

From: http://blog.caboo.se/articles/2006/06/11/stupid-hash-tricks

class Hash

  # lets through the keys in the argument
  # >> {:one => 1, :two => 2, :three => 3}.pass(:one)
  # => {:one=>1}
  def pass(*keys)
    tmp = self.clone
    tmp.delete_if {|k,v| ! keys.include?(k) }
    tmp
  end

  # blocks the keys in the arguments
  # >> {:one => 1, :two => 2, :three => 3}.block(:one)
  # => {:two=>2, :three=>3}
  def block(*keys)
    tmp = self.clone
    tmp.delete_if {|k,v| keys.include?(k) }
    tmp
  end

end


In case you don’t already see the utility of this:
def some_action
    # some script kiddie also passed in :bee, which we don't want tampered with _here_.
    @model = Model.create(params.pass(:foo, :bar))
  end

or those cases where you don’t want to let everything through and don’t want to resort to attr_protected or attr_accessible
« Newer Snippets
Older Snippets »
Showing 1-3 of 3 total  RSS