Posts Tagged 'Code'

Hash to Object

Sometimes I have the need to create objects that responds to some methods with a specific values.
Something that I can use like
HashObject.new :method1 => value_for_method1, :method2 => value_for_method2
There is already a way to do it, with OpenStruct, but I created a HashObject. Just for academic proposals. I didn’t knew the OpenStruct at the time.

class HashObject
  def initialize(hash)
    hash.each do |k,v|
      self.instance_variable_set("@#{k}", v)
      self.class.send(:define_method, k, proc{self.instance_variable_get("@#{k}")})
      self.class.send(:define_method, "#{k}=", proc{|v| self.instance_variable_set("@#{k}", v)})
    end
  end
  
  def to_hash
    hash_to_return = {}
    self.instance_variables.each do |var|
      hash_to_return[var.gsub("@","")] = self.instance_variable_get(var)
    end
    return hash_to_return
  end
end

will_paginate without losing params

I’m sure you like will_paginate, it seams magic! But I was having the issue, that I simply solved like that:

will_paginate(@reports, :params => params.except(:page))



Follow

Get every new post delivered to your Inbox.