Simple Rails Helper for Bypassing Action Logic

When modifying a view, we check the HTML output very often. Sometime refreshing browser is expensive because of the complex controller logic like fetching external resources. We can stub data at the very beginning but we still have to test with real data in some point of time. I wrote a simple rails helper, to memorize all instance variables defined before rendering a view. Then it can be reused for rendering next time.

The Helper

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
def iv_cache
  raise "Block is expected" unless block_given?
  return yield if Rails.env != 'development'
  id = "#{self.controller_path}##{self.action_name}"
  $iv_cache.try :delete, id if params.has_key?(:no_iv_cache)
  if $iv_cache && $iv_cache.has_key?(id)
    $iv_cache[id].each { |k, v|
      self.instance_variable_set(k, v)
    }
  else
    yield
    $iv_cache ||= {}
    $iv_cache[id] = self.instance_variables.each_with_object({}) { |key, h|
      h[key.to_s] = self.instance_variable_get(key)
    }
  end
end

The Controller

1
2
3
4
5
def show
  iv_cache {
    @post = Models::Post.get(params[:id])
  }
end

Comments