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