The Artima Developer Community
Sponsored Link

Ruby Buzz Forum
Hash for views

0 replies on 1 page.

Welcome Guest
  Sign In

Go back to the topic listing  Back to Topic List Click to reply to this topic  Reply to this Topic Click to search messages in this forum  Search Forum Click for a threaded view of the topic  Threaded View   
Previous Topic   Next Topic
Flat View: This topic has 0 replies on 1 page
Guy Naor

Posts: 104
Nickname: familyguy
Registered: Mar, 2006

Guy Naor is one of the founders of famundo.com and a long time developer
Hash for views Posted: May 24, 2006 6:29 PM
Reply to this message Reply

This post originated from an RSS feed registered with Ruby Buzz by Guy Naor.
Original Post: Hash for views
Feed Title: Famundo - The Dev Blog
Feed URL: http://devblog.famundo.com/xml/rss/feed.xml
Feed Description: A blog describing the development and related technologies involved in creating famundo.com - a family management sytem written using Ruby On Rails and postgres
Latest Ruby Buzz Posts
Latest Ruby Buzz Posts by Guy Naor
Latest Posts From Famundo - The Dev Blog

Advertisement

One of my team members asked for a way to use non ActiveRecord objects in views. We settled on a modified hash that will have accessors for all the keys. Pretty simple with method_missing()

class ObjectiveHash < Hash

  def method_missing(method_id, *args, &block)
    begin
      super
    rescue NoMethodError => e
      is_assign = method_id.to_s[-1,1] == '='
      the_key = (method_id.to_s[0..(is_assign ? -2 : -1)]).to_sym
      self[the_key] = args if args && is_assign
      raise e if !self[the_key] 
      return self[the_key]
    end
  end

  private 
  def initialize other_hash
    super
    update(other_hash)
  end

end

Now we can pass it to the view, and retireve into it on submit:

# Setting values
@settings = ObjectiveHash.new
@settings.name = "John"
@settings.family = "Doe"

# Getting values on submit
@settings = ObjectiveHash.new params[:settings].symbolize_keys

# Accessing the values
@settings.name # => John
@settings.family # => Doe

Please note that it'll be slower than regular hash access (which still works), and that all keys are symbols.

Read: Hash for views

Topic: rcov 0.4.0: more accurate code coverage, scriptability, unrotten internals Previous Topic   Next Topic Topic: Please learn how to bid on eBay

Sponsored Links



Google
  Web Artima.com   

Copyright © 1996-2019 Artima, Inc. All Rights Reserved. - Privacy Policy - Terms of Use