Easy Helpers for Sinatra

I am spending more time with Sinatra apps. I think it is a perfect framework to start application with. What I like about Sinatra the most is how easy it is to extend it. Recently I was building a small app, that processes user provided templates and was looking for an easy way to add template components (helpers) to give customers a sort of DSL to work with. What I ended up doing was the following:

module Components
  components_path = File.expand_path(File.dirname(__FILE__) + '/components')

  files = Dir.new(components_path).select{|f| f =~ /.*\.rb/ } || []
  files.each do |f|
    body = File.new(File.join([components_path, f])).read
    name = File.basename(f, '.rb').capitalize + "Helper"
    module_eval <<-"end;"
      module #{name}


Link to the file: http://gist.github.com/141220

As you can see this pretty simple Ruby magic allows me to put my “components” into a subdirectory and add them all as Sinatra helpers. Since the body of the component is wrapped into a module, component development becomes very easy. Following code, once saved into components directory will add a search helper to your app:

def search(options = {})

Pretty simple, but still fun 🙂


About Wondering Bear
39 years old male bear.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s

%d bloggers like this: