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}
#{body}
end
end;
Sinatra.helpers(const_get(name))
end
end
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 = {})
......
end
Pretty simple, but still fun