From f3779cd2c9144873efbba6aef013de47c189b30f Mon Sep 17 00:00:00 2001 From: Skud Date: Mon, 19 Aug 2013 23:52:29 +1000 Subject: [PATCH] Quick links to crop pages in Markdown. --- lib/haml/filters/growstuff_markdown.rb | 31 +++++++++++++++ .../haml/filters/growstuff_markdown_spec.rb | 39 +++++++++++++++++++ 2 files changed, 70 insertions(+) create mode 100644 lib/haml/filters/growstuff_markdown.rb create mode 100644 spec/lib/haml/filters/growstuff_markdown_spec.rb diff --git a/lib/haml/filters/growstuff_markdown.rb b/lib/haml/filters/growstuff_markdown.rb new file mode 100644 index 000000000..78f481161 --- /dev/null +++ b/lib/haml/filters/growstuff_markdown.rb @@ -0,0 +1,31 @@ +require 'bluecloth' +include ActionDispatch::Routing +include Rails.application.routes.url_helpers + +module Haml::Filters + module GrowstuffMarkdown + include Haml::Filters::Base + + def render(text) + bc = BlueCloth.new(text) + orig = bc.text + + # turn [tomato](crop) into [tomato](http://growstuff.org/crops/tomato) + return orig.gsub(/\[(.*?)\]\(crop\)/) do |m| + crop_str = $1 + crop = Crop.find_by_system_name(crop_str) + if crop + url = url_for(crop_path(crop)) + "[#{crop_str}](#{url})" + else + crop_str + end + end + end + end + +# Register it as the handler for the :growstuff_markdown HAML command. +# The automatic system gives us :growstuffmarkdown, which is ugly. +defined['growstuff_markdown'] = GrowstuffMarkdown + +end diff --git a/spec/lib/haml/filters/growstuff_markdown_spec.rb b/spec/lib/haml/filters/growstuff_markdown_spec.rb new file mode 100644 index 000000000..73f4161ba --- /dev/null +++ b/spec/lib/haml/filters/growstuff_markdown_spec.rb @@ -0,0 +1,39 @@ +require 'spec_helper' +require 'haml/filters' +require 'haml/filters/growstuff_markdown' +# require 'haml/helpers' + +def input_link(name) + return "[#{name}](crop)" +end + +def output_link(crop) + return "[#{crop.system_name}](#{crop_path(crop)})" +end + +describe 'Haml::Filters::Growstuff_Markdown' do + it 'is registered as the handler for :growstuff_markdown' do + Haml::Filters::defined['growstuff_markdown'].should == + Haml::Filters::GrowstuffMarkdown + end + + it 'converts quick crop links' do + @crop = FactoryGirl.create(:crop) + rendered = Haml::Filters::GrowstuffMarkdown.render(input_link(@crop.system_name)) + rendered.should eq output_link(@crop) + end + + it "doesn't convert nonexistent crops" do + rendered = Haml::Filters::GrowstuffMarkdown.render(input_link("not a crop")) + rendered.should eq "not a crop" + end + + it "handles multiple crop links" do + tomato = FactoryGirl.create(:tomato) + maize = FactoryGirl.create(:maize) + string = "#{input_link(tomato)} #{input_link(maize)}" + rendered = Haml::Filters::GrowstuffMarkdown.render(string) + rendered.should eq "#{output_link(tomato)} #{output_link(maize)}" + end + +end