From 78f8245c208c339523f3d4c72666ff7f5caee854 Mon Sep 17 00:00:00 2001 From: Thomas Reynolds Date: Fri, 29 Apr 2011 11:58:07 -0700 Subject: [PATCH] remote data sources and indifferent access. closes #44 --- lib/middleman/features/data.rb | 51 +++++++++++++++++++++++++++++++++- middleman.gemspec | 1 + 2 files changed, 51 insertions(+), 1 deletion(-) diff --git a/lib/middleman/features/data.rb b/lib/middleman/features/data.rb index 349cdb9e..d0ba03df 100755 --- a/lib/middleman/features/data.rb +++ b/lib/middleman/features/data.rb @@ -1,8 +1,11 @@ require "yaml" +require "httparty" +require "thor" module Middleman::Features::Data class << self def registered(app) + app.extend ClassMethods app.helpers Middleman::Features::Data::Helpers end alias :included :registered @@ -20,11 +23,57 @@ module Middleman::Features::Data end def method_missing(path) + response = nil + + @@remote_sources ||= {} + if @@remote_sources.has_key?(path.to_s) + response = HTTParty.get(@@remote_sources[path.to_s]).parsed_response + end + file_path = File.join(@app.class.root, "data", "#{path}.yml") if File.exists? file_path - return YAML.load_file(file_path) + response = YAML.load_file(file_path) + end + + if response + recursively_enhance(response) + end + end + + def self.add_source(name, json_url) + @@remote_sources ||= {} + @@remote_sources[name.to_s] = json_url + end + + private + def recursively_enhance(data) + if data.is_a? Hash + data = Thor::CoreExt::HashWithIndifferentAccess.new(data) + data.each do |key, val| + data[key] = recursively_enhance(val) + end + data + elsif data.is_a? Array + data.each_with_index do |val, i| + data[i] = recursively_enhance(val) + end + data + else + data end end end + module ClassMethods + # Makes HTTP json data available in the data object + # + # data_source :my_json, "http://my/file.json" + # + # Available in templates as: + # + # data.my_json + def data_source(name, url) + Middleman::Features::Data::DataObject.add_source(name, url) + end + end end \ No newline at end of file diff --git a/middleman.gemspec b/middleman.gemspec index 1188fe82..32c25baf 100644 --- a/middleman.gemspec +++ b/middleman.gemspec @@ -35,6 +35,7 @@ Gem::Specification.new do |s| s.add_runtime_dependency("sass", ["~> 3.1.0"]) s.add_runtime_dependency("compass", ["~> 0.11.1"]) s.add_runtime_dependency("coffee-script", ["~> 2.1.0"]) + s.add_runtime_dependency("httparty", ["~> 0.7.0"]) # s.add_runtime_dependency("fssm", ["~> 0.2.0"]) s.add_development_dependency("cucumber", ["~> 0.10.0"]) s.add_development_dependency("rspec", [">= 0"])