Monday, 15 December 2014

12 Tips of Christmas - 5 Rendering a Hash with OpenStruct

12 Tips of Christmas - 5 Rendering a Hash with OpenStruct

OpenStruct is pretty fantastic, it let's you arbitrarily create attributes, which is fantastic if you have some dynamically generated hashes you need to work with. 
One of the really cool tricks you can do, is take that OpenStruct and render it, this is incredibly useful for sending out text messages, all you need is a little ERB.
to start, create your rendering object:
require 'ostruct'
require 'erb'

class SmsRenderer < OpenStruct  
  def render(template)
    ERB.new(template).result(binding)
  end
end
Now we have an object capable of rendering, all we need to do is give it a template, and a Hash with some attributes, like so:
def sms_template_render file_name, options = {}
  rendering_obj = SmsRenderer.new(options)
  template = File.open("#{Rails.root}/app/views/sms/#{file_name}.text.erb").read
end
Now you can use those lovely erb tags in your text message templates! 
If we just call the above method when passing content to your SMS send method, you'll get the dynamic text messages you're after.

No comments:

Post a Comment